零初始化数组的数据成员在构造函数 [英] Zero-initializing an array data member in a constructor

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

问题描述

我有类对象的数组,类对象里面我已经得到了另一个数组,我需要初始化为全零。在code编译和运行,但我的输出显示Ç
而不是0。

I've got an array of class objects, and inside the class object I've got another array that I'd need to initialize to all zeros. The code compiles and runs, but my output is showing C rather than 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文件

from the other cpp file

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的预期。

Is this being set up correctly? As I mentioned, getBytes is returning 'C's rather than '0's as expected.

推荐答案

只需使用的值初始化的构造函数初始化列表。这是C ++这样的习惯的方法。

Just use value initialization in the constructor initialization list. That is the idiomatic way of doing this in C++.

Cache::Cache() : byte()
{ 
}

需要注意的是C ++ 11允许这种语法太:

Note that C++11 allows this syntax too:

Cache::Cache() : byte{}
{ 
}

如果你想知道的为什么的这部作品,从C ++标准11(注意,这也适用于C ++ 03):

In case you're wondering why this works, from the C++ 11 standard (note this also applies to C++03):

C ++ 11§8.5,P10

其初始化为空括号的一个目的,即(),应值初始化

An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.

这是长期的值初始化的把我们带到了:

That term value-initialized takes us to:

C ++ 11§8.5,P7

要值初始化类型T的对象是指:

To value-initialize an object of type T means:


      
  • 如果T是一个(可能被cv修饰)类类型 9 与用户提供的构造函数(12.1),则T的默认构造函数(和初始病-formed如果T没有访问的默认构造函数);

  • 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);

如果T是一个(可能被cv修饰)非工会类没有用户提供的构造类型,那么对象被初始化为零,如果T的隐式声明的默认构造函数是不平凡的,这构造函数被调用。

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.

如果T是数组类型,那么每一个元素都是值初始化;

,否则,该对象被初始化为零。

在此第三个选项时刻表的每个元件的值初始化;第四适用,一旦我们得到各个元素,因为它们是(a)任何类类型,所以(1)和(2)都走了,和(b)不是数组,所以(3)走了。现在只剩最后一个,你的元素零初始化。

The third option in this trips the value-initialization of each element; the fourth applies once we get to each of those elements because they're (a) no class types, so (1) and (2) are gone, and (b) not arrays, so (3) is gone. That leaves only the last one, and your elements are zero-initialized.

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

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