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 ?."
您缺少的是 initialisation 发生在初始化列表中,而 assignment 发生在构造函数的主体中.逻辑步骤:
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 成员必须在构造函数初始化器中而不是在其主体中初始化?
基础教程推荐
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
