我有一个类对象数组,在类对象中我有另一个数组,我需要将其初始化为全零。代码编译并运行,但我的输出显示 C 而不是 0。
来自头文件:
class Cache {
private:
int byte[16];
public:
Cache();
int getBytes(int);
~Cache();
};
来自cpp文件
Cache::Cache()
{
byte[16]={0};
}
int Cache::getBytes(int j){
return byte[j];
}
来自其他cpp文件
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++) //visual check of initializes main memory
{
cout << cache[i].getBytes(j) << " ";
}
}
设置是否正确?正如我提到的,getBytes 返回的是“C”而不是预期的“0”。
最佳答案
只需在构造函数初始化列表中使用值初始化。这是在 C++ 中执行此操作的惯用方法。
Cache::Cache() : byte()
{
}
注意 C++11 也允许这种语法:
Cache::Cache() : byte{}
{
}
如果您想知道为什么这是有效的,根据 C++ 11 标准(注意这也适用于 C++03):
C++11 § 8.5,p10
An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
value-initialized 一词将我们带到:
C++11 § 8.5,p7
To value-initialize an object of type T means:
if T is a (possibly cv-qualified) class type9 with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.
if T is an array type, then each element is value-initialized;
otherwise, the object is zero-initialized.
这里的第三个选项触发每个元素的值初始化;第四个适用于我们到达这些元素中的每一个,因为它们 (a) 没有类类型,所以 (1) 和 (2) 消失了,并且 (b) 不是数组,所以 (3) 消失了。这只剩下最后一个,你的元素被零初始化。
关于c++ - 在构造函数中零初始化数组数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23987515/