我最近在 Danny Kalev 的文章 Why can't member initializers use parentheses? 中发现了一段有趣的代码:
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");
};`)无法编译
- Get to Know the New C++11 Initialization Forms (编译器参数是
-std=c++11 -Wall -Wextra -Werror -pedantic-errors
) - clang 3.6.1 (编译器参数相同:
-std=c++11 -Wall -Wextra -Werror -pedantic-errors
) - g++ 5.1.0 (编译器参数是
/EHsc /Wall /wd4514 /wd4710 /wd4820 /WX /Za
) - vc++ 18.00.21005.1(编译器参数由服务预定义:
/EHsc /nologo /W4 /c
)
我说得对吗?这篇文章有错误吗?
最佳答案
Am I right and there is an error in this article?
是的,文章中有一个错误。
数据成员的声明中只允许使用大括号或等于初始值设定项。 d
、p
和 y
的初始化是正确的,但 s
的初始化不正确。这样做的理由是,使用表达式列表会使声明与函数声明产生歧义,并且还会导致与类主体中的名称查找发生冲突。
关于c++ - 使用构造函数的类内成员初始值设定项 : is it allowed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671332/