我最近在Danny Kalev的文章Get to Know the New C++11 Initialization Forms中找到了一段有趣的代码:
class C
{
string s("abc");
double d=0;
char * p {nullptr};
int y[5] {1,2,3,4};
public:
C();
};
string s("abc");
行对我来说似乎很可疑。我认为在成员在类中初始化时不允许使用构造函数。
这段代码(简化为class C { string s("abc");
};`)不用
-std=c++11 -Wall -Wextra -Werror -pedantic-errors
)-std=c++11 -Wall -Wextra -Werror -pedantic-errors
)/EHsc /Wall /wd4514 /wd4710 /wd4820 /WX /Za
)/EHsc /nologo /W4 /c
)我是对的,这篇文章中有错误吗?
答案 0 :(得分:4)
我是对的,这篇文章中有错误吗?
是的,这篇文章中的错误。
在数据成员的声明中只允许大括号或等于初始化。 d
,p
和y
的初始化是正确的,但不是s
。这样做的理由是,使用表达式列表会使用函数声明模糊声明,并且还会导致与类体中的名称查找冲突。
答案 1 :(得分:1)
An example from Bjarne Stroustrup:
class A {
public:
A() {}
A(int a_val) : a(a_val) {}
A(D d) : b(g(d)) {}
int a = 7;
int b = 5;
private:
HashingFunction hash_algorithm{"MD5"}; // Cryptographic hash to be applied to all A instances
std::string s{"Constructor run"}; // String indicating state in object lifecycle
};