我必须初始化简单的类成员变量吗? [英] Do I have to initialize simple class member variables?

查看:180
本文介绍了我必须初始化简单的类成员变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速入门的问题:

我可以初始化简单的类成员变量,或者保证它们被赋予默认值任何情况?

Do I have to initialize simple class member variables, or are they guaranteed to get assigned their default values in any case?

示例:

class Foo {
  int i;
  // is i==0 or do I need the following line for that?
  Foo() : i(0) {}
};


$ b

谢谢!

Thanks!

推荐答案


我必须初始化简单类
的成员变量,

Do I have to initialize simple class member variables,

不,您不会初始化成员变量。如果你不初始化它们,不要假设它们有任何值。

No, you don't have to initialize the member variables. If you do not initialize them though, do not assume they will have any value.

如果你做一个测试程序,并检查调试器如何初始化值,你可能会看到他们初始化为零,但这不能保证。这些值会被初始化为堆栈中内存中的任何内容。

If you make a test program and check in debugger how the values are initialized you may see them initialized as zeros, but that is not guaranteed. The values get initialized to whatever is in memory on the stack at that location.


或者他们保证会分配
默认值在任何情况下?

or are they guaranteed to get assigned their default values in any case?

它们不能保证获得分配任何值。如果你有成员对象,将为它们调用默认构造函数,但对于POD类型没有默认初始化。

They are not guaranteed to get assigned any value. If you have member objects the default constructors will be called for them, but for POD types there is no default initialization.

即使你不必这样做,最好是初始化您的类的所有成员(避免很难找到错误并明确表示初始化/构造函数调用)。

Even though you don't have to do it, it is good practice to initialize all members of your class (to avoid hard to find errors and to have an explicit representation of the initializations / constructor calls).

这篇关于我必须初始化简单的类成员变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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