【发布时间】:2012-10-15 06:36:19
【问题描述】:
当我尝试编译下面的源代码时出现以下错误。谁能描述为什么会出现这个错误以及我该如何解决?
错误 1 错误 C2758: 'A::s_' : 必须在构造函数基/成员初始化器中初始化
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A(string& s) : s_(s) { cout << "A::ctor" << endl; }
A(const A& rhs) { cout << "A::copy" << endl; }
~A() { cout << "A::dtor" << endl; }
A& operator=(const A& rhs) { cout << "A::copyassign" << endl; }
private:
string& s_;
};
int main()
{
return 0;
}
【问题讨论】:
-
当你有一个引用成员时,你不能真正拥有一个语义上有效的赋值运算符。您不能将其重新分配给不同的字符串。它只会修改被引用的原始字符串。
标签: c++ constructor compiler-errors visual-studio-2012