如何在此默认构造函数中初始化对空字符串 ("") 的类成员引用。
class Document {
string& title;
string* summary;
Document() : title(/*what to put here*/), summary(NULL) {}
};
最佳答案
没有明智的方法可以做到这一点。引用必须引用现有对象(更好的说法是引用 是 现有对象),而 std::string
将是从 ""
构造的初始化列表将在构造函数完成后被销毁,每次尝试使用您的成员变量时都会留下未定义的行为。
现在,我说“没有明智的方法”。当然,有一些黑客可以实现你想要的,例如:
// bad hack:
std::string &EmptyStringThatLivesForever()
{
static std::string string;
return string;
}
class Document {
string& title;
string* summary;
Document() : title(EmptyStringThatLivesForever()), summary(NULL) {}
};
但我怀疑这样的技巧能否经受住任何严格的代码审查。
真正的解决办法是去掉引用:
class Document {
string title;
string* summary;
Document() : title(""), summary(NULL) {}
};
关于c++ - 如何在默认构造函数中初始化对空字符串的类成员引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659278/