我有一个这样的类。我想对字符串使用引用,但它不起作用。我如何使用 string& ?
#include <string>
using namespace std;
class T
{
public:
T(string& s);
private:
string s;
};
T::T(string& s)
{
this->s = s;
}
int main(void)
{
T t("Test Object");
return 0;
}
Error : 'T::T(std::string &)' : cannot convert parameter 1 from 'const char [12]' to 'std::string &'
最佳答案
使用 const
:
class T
{
public:
T(const string& ss);
private:
string s;
};
T::T(const string& ss) : s(ss)
{
}
"Test Object"
在传递给 T
的构造函数之前将构造为 const
string
,所以构造函数必须接受一个 const string
。
关于c++ - 使用字符串引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15360555/