我假设必须在类构造函数中初始化const
成员。
考虑以下代码
class ABC
{
const string a;
const string b;
const string c;
public:
ABC( struct input in): a(in.a), b(in.b){}
};
我认为这会触发编译时错误,因为缺少c
的显式初始化。但是,这会在VS2012下编译并为c
提供空字符串。这是正确的行为吗? (或string
的特殊情况?)
答案 0 :(得分:0)
const member must be initialized when declared
以上仅适用于内置和POD类型。对于非POD类型,将调用默认构造函数来初始化它。
std::string
是非POD。
如@Dan的评论中所述,尝试将const string c;
更改为const int c;
,编译器会抱怨。