简体   繁体   English

零在类构造函数C ++中初始化多维数组

[英]Zero initialize multidimentional array in class constructor C++

Is there a way (with C++11) to zero-initialize a multidimensional array in a class constructor? 有没有办法(使用C ++ 11)在类构造函数中初始化多维数组?

Does this initialize the whole array to zero or just the first dimension? 这会将整个数组初始化为零还是仅初始化第一维?

class Example
{
public:
    int array[100][100];

    Example():array{}
    {
    };
};

Lastly, will this work with enumerated types? 最后,这将使用枚举类型吗?

Value-initialization for an array will value-initialize each element in the array. 数组的值初始化将对数组中的每个元素进行值初始化。 You have an array of arrays, so each element (an array) will be value-initialized. 您有一个数组数组,因此每个元素(一个数组)都将进行值初始化。 From there, return to the first sentence of this answer for what happens to each array. 从那里,返回到每个数组发生的事情的答案的第一句话。

The answer to your second question, regular enumerations are scalars, and as such are value-initialized, just like your int values in your array, which is to say they're zero-initialized . 对于第二个问题的答案,常规枚举是标量,因此是值初始化的,就像数组中的int值一样,也就是说它们是零初始化的 That may be problematic if you have an enum without a 0-value representation: 如果你有一个没有0值表示的枚举,这可能会有问题:

#include <iostream>

enum EnumStuff
{
    one = 1,
    two = 2,
    three = 3
};

int main()
{
    EnumStuff arr[10][10]{};
    for (auto const&x : arr)
    {
        for (auto y : x)
            std::cout << static_cast<int>(y) << ' ';
        std::cout << '\n';
    }
}

There is no 0-value in EnumStuff . EnumStuff没有0值。 Just something to keep in mind. 请记住一些事情。 A switch looking for only those three values, for example, will be sorely-disappointed (and shortly thereafter, likely you with it). 例如, 仅仅寻找这三个值的switch将会非常失望(此后不久,很可能会使用它)。

Best of luck 祝你好运

多维数组的值初始化(即使用{} )值初始化所有元素,因此所有10000个元素的值都为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM