为什么 const 成员必须在构造函数初始值设定项中初始化,而不是在其主体中初始化?
为什么声明为 const 的类成员必须在构造函数初始值设定项列表中而不是在构造函数主体中初始化?
两者有什么区别?
Why must class members declared as const
be initialized in the constructor initializer list rather than in the constructor body?
What is the difference between the two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++ 中,当执行进入构造函数主体时,对象被视为完全初始化。
你说:
您缺少的是初始化发生在初始化列表中,而赋值发生在构造函数的主体中。逻辑步骤:
1) const 对象只能被初始化
2) 一个对象的所有成员都在初始化列表中初始化,即使您没有在那里显式初始化它们,编译器也会很乐意为您这样做:-)
3) 因此。 ,将 1) 和 2) 放在一起,const 成员只能在初始化时分配一个值,这发生在初始化列表期间。
In C++, an object is considered fully initialised when execution enters the body of the constructor.
You said:
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) A const object can only be initialised.
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) 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 或引用成员变量值是不够的。
C++ 提供了另一种初始化成员变量的方法,允许在创建成员变量时而不是事后对其进行初始化。 这是通过使用初始化列表来完成的。
您可以通过两种方式为变量赋值:显式和隐式:
查看纯文本复制到剪贴板打印?
使用初始化列表与执行隐式赋值非常相似。
请记住,用于初始化基类和成员数据对象的成员初始化列表位于定义中,而不是构造函数的声明中。
更多关于 cpp-tutorial 和 代码牧马人。
const
and reference variables must be initialized on the line they are declared.would produce code equivalent to;
Assigning const or reference member variables values in the body of the constructor is not sufficient.
C++ provides another way of initializing member variables that allows to initialize member variables when they are created rather than afterwards. This is done through use of an initialization list.
You can assign values to variables in two ways: explicitly and implicitly:
view plaincopy to clipboardprint?
Using an initialization list is very similar to doing implicit assignments.
Remember that the member initialization list, used to initialize base and member data objects, is in the definition, not declaration of the constructor.
More on cpp-tutorial and Code Wrangler.
因为常量变量和引用必须在声明时(即使用前)初始化。
但是构造函数会将值分配给变量而不是初始化变量,因此您必须使用常量和引用的初始化列表
Because constant variables and references must be initialized at time of declaration i.e before use.
But Constructors will assign value to a varaible not initailize the variable therefore you must use initailizier list for constant and references