【发布时间】:2014-05-07 02:31:09
【问题描述】:
在构造函数 C++ 标准中修改 const 吗?我正在修改我的 struct 删除固定值(默认成员初始值设定项)以稍后在构造函数时设置它,但我忘记删除 const 关键字并稍后注意到它。令我惊讶的是,我没有收到编译错误,它运行良好,但对于测试用例 2,它提供了一个编译器。它们有何不同?
测试用例 1:
struct A
{
const int x = 2;
A()
: x(3)
{
}
};
测试用例 2:
struct A
{
const int x = 2;
A()
{
x = 3; // compile error! error: read-only variable is not assignable
}
};
【问题讨论】:
-
见this question。似乎相关。
标签: c++ constructor initialization constants