考虑代码片段
class Test{
const int i;
public:
// Test(int x):i(x){} This works
Test(int x){
i=x;
} //this doesn't work
为什么内联成员初始化列表可以工作,而普通初始化却不起作用?
最佳答案
请注意,i=x;
是一个赋值。如果您不通过成员初始化器列表初始化它,i
将尝试默认初始化,然后在构造函数的主体中分配。
但作为 const 变量,i
不能默认初始化(或赋值)。所以必须在 member intializer list 中指定它用于初始化。
Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.
关于c++ - 常量变量初始化仅适用于成员初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758193/