构造函数是否应该初始化该类的所有数据成员? [英] Should constructor initialize all the data members of the class?

查看:570
本文介绍了构造函数是否应该初始化该类的所有数据成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况:

class A {
public:
  A() : n(0) {}
private:
  int n;
  int m;
}

在应用程序逻辑中,根本没有意义在构造函数中初始化m.但是,Eclipse警告我构造函数将m保留为未初始化状态.我现在无法在其他地方运行代码.警告是:

There is simply no meaning in the application logic to initialize m in the constructor. However, Eclipse warns me that the constructor leaves m uninitialized. I can't run the code somewhere else now. The warning is:

成员"m"未在此构造函数中初始化

Member 'm' was not initialized in this constructor

那么,C ++是否鼓励我们初始化构造函数中的所有数据成员,或者这仅仅是Eclipse的逻辑?

So, does C++ encourage us to initialize all the data members in the constructor or it is just Eclipse's logic?

推荐答案

构造函数应初始化类的所有数据成员吗?

Should constructor initialize all the data members of the class?

那将是一个好习惯.

那么,C ++是否鼓励我们初始化构造函数中的所有数据成员?

So, does C++ encourage us to initialize all the data members in the constructor?

c ++标准不是必需的.只要您在使用所有变量之前对其进行初始化,就此而言,您的程序是正确的.

It's not required by the c++ standard. As long as you initialize all variables before they're used, your program is correct in that regard.

还是仅仅是Eclipse的逻辑?

or it is just Eclipse's logic?

很有可能.启用所有警告后,我测试过的g ++和clang版本均未对此发出警告.该逻辑可能基于或不基于

Quite likely. Neither g++ nor clang versions that I tested warn about this when all warnings are enabled. The logic may or might not be based on high integrity c++ coding standard 12.4.2 or some other coding standard or style guide.

这篇关于构造函数是否应该初始化该类的所有数据成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆