为什么必须在构造函数初始化器中而不是在它的主体中初始化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?
在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) 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.