Why can const members be modified in a constructor?(为什么可以在构造函数中修改 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
};
这篇关于为什么可以在构造函数中修改 const 成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么可以在构造函数中修改 const 成员?
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01