为什么可以在构造函数中修改 const 成员?
我很好奇为什么可以在构造函数中修改 const 成员.
I'm curious why const members can be modified in the constructor.
初始化中是否有任何标准规则可以覆盖成员的常量"?
Is there any standard rule in initialization that overrides the "const-ness" of a member?
struct Bar {
const int b = 5; // default member initialization
Bar(int c):b(c) {}
};
Bar *b = new Bar(2); // Problem: Bar::b is modified to 2
// was expecting it to be an error
有什么想法吗?
推荐答案
这不是修改(或赋值),而是 初始化.例如
This is not modification (or assignment) but initialization. e.g.
struct Bar {
const int b = 5; // initialization (via default member initializer)
Bar(int c)
:b(c) // initialization (via member initializer list)
{
b = c; // assignment; which is not allowed
}
};
const
数据成员无法修改或分配,但可以(并且需要)通过成员初始化器列表或默认成员初始化器进行初始化.
The const
data member can't be modified or assigned but it could (and need to) be initialized via member initializer list or default member initializer.
如果在同一个数据成员上同时提供了默认成员初始化器和成员初始化器,则默认成员初始化器将被忽略.这就是为什么 b->b
被初始化为值 2
.
If both default member initializer and member initializer are provided on the same data member, the default member initializer will be ignored. That's why b->b
is initialized with value 2
.
如果一个成员有一个默认的成员初始化器,并且还出现在构造函数的成员初始化列表中,则忽略默认的成员初始化器.
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.
另一方面,默认成员初始化器只有在成员初始化器列表中没有指定数据成员时才会生效.例如
On the other hand, the default member initializer takes effect only when the data member is not specified in the member initializer list. e.g.
struct Bar {
const int b = 5; // default member initialization
Bar(int c):b(c) {} // b is initialized with c
Bar() {} // b is initialized with 5
};
相关文章