简体   繁体   English

类实例成员初始化

[英]class instance member initialisation

If a class has an instance member that is itself a class, does the constructor ALWAYS have to provide an initialisation for it in the constructor initialiser list? 如果一个类的实例成员本身就是一个类,那么构造函数是否总是必须在构造函数初始化列表中为其提供初始化?

In some cases in my code this leads to very long initialiser lists, is this the way to do things? 在我的代码中的某些情况下,这导致了很长的初始化列表,这是做事的方式吗? I only ask because it looks inelegant, but if it's how it's done then that's fine. 我只是问,因为它看起来不优雅,但如果它是如何完成那么那很好。

is the same also the case for constant instance member variables? 常量实例成员变量也一样吗?

If you have a default constructor (without parameters) - then you don't need to explicitly initialize it. 如果您具有默认构造函数(不带参数),则无需显式初始化它。

For constant instances, there's no point in having default initialization, is there? 对于常量实例,默认初始化没有意义,是吗? So it wouldn't make sense to have them at all, unless you have something to initialize them with. 因此,完全没有它们是没有意义的,除非您有一些初始化它们的方法。 (But it is of course possible, if for whatever reason that's what you're doing). (但是,出于某种原因,这当然是可能的)。

For objects , you will have to initialize all members that do not have a default constructor . 对于对象 ,您必须初始化没有默认构造函数的所有成员 If you omit a member in the initialization list, its default constructor will be used (or its value will be undefined for primitive types). 如果在初始化列表中省略成员,则将使用其默认构造函数(或对于原始类型,其值将是未定义的)。

For primitive types ( int , pointers ), it is legal not to initialize them, but their value will be undefined . 对于原始类型intpointers ),初始化它们是合法的,但它们的值将是未定义的

Finally, you must initialize references to other objects ( std::string& ). 最后,您必须初始化对其他对象的引用std::string& )。

See this answer for more. 请参阅此答案了解更多信息

Additionally, I'd like to point out that if your class has many members, it may be a sign that you should split it into several smaller classes. 另外,我想指出,如果你的班级有很多成员,这可能表明你应该将它分成几个较小的类。 The best practice is to have classes which only have one responsibility (see single responsibility principle ). 最佳做法是设立只有一种责任的课程(参见单一责任原则 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM