问题描述
一个关于c ++编码风格的简单问题,
Just a simple question about c++ coding style,
例如,如果我们不做任何其他操作,则将使用初始化列表中的默认构造函数调用类的所有成员变量. B默认构造函数将被调用,并且值将被设置为0,int();
for example, all member variables of a class will be called with the default constructor in the initialization list if we don't do anything else. B default constructor will be called and value will be set to 0, int();
class A
{
A();
private:
B b;
int value;
}
但是我的问题是,即使是默认的构造函数也会被调用吗,这是一个总是自己做的好习惯,还是只会在代码中添加额外的行
However my question is, even do the default constructor will be called is it a good habit to always do it yourself or does it only add extra lines to the code
推荐答案
最好保留默认构造函数.编译器生成的构造函数比编写您自己的版本更可靠和可维护,并且除其他事项外,浪费时间来编写编译器可以为您编写的代码.如果不需要任何构造逻辑,请不要编写构造函数.
It's a good idea to leave the default constructor out. The compiler-generated constructors are much more reliable and maintainable than writing your own versions, and apart from anything else, it's a flat out waste of time to write code the compiler could write for you. If you don't need any construction logic, then don't write a constructor.
但是,除非您执行int
的操作,否则不会初始化int
,这是不得不编写构造函数的麻烦原因.
However, the int
will not be initialized unless you do it, which is a sucky reason to have to write a constructor.
这篇关于类初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!