c++成员初始化列表完整性
C++ 中的类成员初始化列表必须完整吗?或者他们可以简单地初始化类中的一两个成员数据吗?
提前致谢!
must class member initialization lists in c++ be complete? or can they simply initialize one or two of the member data in a class?
thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们不必是完整的。您可以省略基类和非POD 类类型,它们是默认可构造的 POD 类型但将保持未初始化状态。
显然,常量成员和引用必须在成员初始化列表中进行初始化。
They don't have to be complete. You can leave out base classes and non-POD class types that are default constructible, POD-types however will be left uninitialized.
Obviously constant members and references have to be initialized in the member initialization list.
int
确实有一个构造函数,请参见 Stroustrup C++ 编程语言第 6.2.8 节这将 j 初始化为 0(对于内置类型显式使用构造函数的值是 0 转换为该类型,因此 int() 是 0 的另一种写法。
内置类型的默认构造函数非常重要,这样模板就可以毫无顾虑地调用默认构造函数,即使对于内置类型也是如此。
int
does have a constructor, see Stroustrup The C++ Programming Language section 6.2.8This initializes j to 0 (The value of an explicit use of the constructor for a built-in type is 0 converted to that type, thus int() is another way of writing 0.
Default constructors for built-in types are important so that templates can invoke default constructors without worry, even for built in types.
不,它们不必是完整的 - 其中未指定的任何成员都将是默认构造的(这包括任何基类)。
显然,任何不可默认构造的成员都必须显式初始化。还有一个小问题 - 整数或浮点数等类型不会被初始化,因此它们的初始值将是未定义的。
No, they don't have to be complete - any members which aren't specified in it will be default-constructed (this includes any base classes).
Obviously, any members which aren't default-constructible must be explicitly initialised. And a small gotcha - types like integers or floats etc will not be initialised, so their initial value will be undefined.