Why must const members be initialized in the constructor initializer rather than in its body?(为什么必须在构造函数初始值设定项中而不是在其主体中初始化 const 成员?)
问题描述
为什么声明为 const
的类成员必须在构造函数初始值设定项列表中而不是在构造函数体中进行初始化?
Why must class members declared as const
be initialized in the constructor initializer list rather than in the constructor body?
两者有什么区别?
推荐答案
在 C++ 中,当执行进入构造函数体时,对象被视为完全初始化.
In C++, an object is considered fully initialised when execution enters the body of the constructor.
你说:
"我想知道为什么 const 必须是在构造函数初始化器中初始化列表而不是它的正文?."
"i wanted to know why const must be intialized in constructor initializer list rather than in it's body ?."
您缺少的是初始化发生在初始化列表中,而赋值发生在构造函数的主体中.逻辑步骤:
What you are missing is that initialisation happens in the initialisation list, and assignment happens in the body of the constructor. The steps in logic:
1) const 对象只能被初始化.
1) A const object can only be initialised.
2) 一个对象的所有成员都在初始化列表中进行了初始化.即使你没有在那里显式地初始化它们,编译器也会很乐意为你这样做:-)
2) An object has all of its members initialised in the initialisation list. Even if you do not explicitly initialise them there, the compiler will happily do so for you :-)
3) 因此,将 1) 和 2) 放在一起,一个 const 成员只能在初始化时分配给它一个值,这发生在初始化列表中.
3) Therefore, putting 1) and 2) together, a member which is const can only ever have a value assigned to it at initialisation, which happens during the initialisation list.
这篇关于为什么必须在构造函数初始值设定项中而不是在其主体中初始化 const 成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么必须在构造函数初始值设定项中而不是在其主体中初始化 const 成员?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01