c++ - 使用字符串引用

标签 c++ reference

我有一个这样的类。我想对字符串使用引用,但它不起作用。我如何使用 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/

相关文章:

multithreading - 如何将对堆栈变量的引用传递给线程?

c++ - vector 引用operator []线程安全写吗?

c# - 带有 ref 变量的 Func 委托(delegate)

C++ 错误 : 'no matching function for call to [class]::[function]'

c++ - 如何保存 TRichEdit 文本 RTF 的特定部分(c++ codegear)

reference - 有没有办法返回对函数中创建的变量的引用?

c - 对函数调用的 undefined reference ?

c++ - MAC OSX Xcode 9.2链接程序命令失败,退出代码为1(使用-v查看调用)

c++ - 为什么 "0f"在 C++ 中不被视为浮点文字?

c++ - 函数重载、继承和隐式构造函数 : weird priority