The*_*ask 6 c++ constructor initialization const
在构造函数C++标准中修改const吗?我正在修改我的struct删除固定值(默认成员初始化程序)以便稍后在构造函数时设置它,但我忘记删除const关键字并稍后通知它.令我惊讶的是,我没有得到编译错误,它只是工作正常,但对于测试用例2,它给出了一个编译器.他们有什么不同?
测试案例1:
struct A
{
const int x = 2;
A()
: x(3)
{
}
};
Run Code Online (Sandbox Code Playgroud)
测试案例2:
struct A
{
const int x = 2;
A()
{
x = 3; // compile error! error: read-only variable is not assignable
}
};
Run Code Online (Sandbox Code Playgroud)