繁体   English   中英

将多维数组初始化为 c++ 中的 class 成员

[英]Initialize a multidimensional array as a class Member in c++

我有一个 class,让我们说:

class Foo
{
    public:

         unsigned int Index;
         float Size;
         Foo(const unsigned int index);
         ~Foo();

    private:
         int Children[2][2];

};

我想在构造函数中初始化 Children 参数:

Foo::Foo(const unsigned int index) : Index(index)
{
    this->Size = 0.5 / index;
    this->Children = {};

    if (index < MAX_DIVS) {
        for (int _x = 0; _x < 2; _x++) {
            for (int _y = 0; _y < 2; _y++) {
                this->Children[_x][_y] = 0;
        }

    }

}

我可以将初始值分配给Size执行this->Size= 0.5/Index ,但我无法初始化 Children; Visual Studio 在this->Children = {}上给我一个错误,说:“表达式必须有一个可修改的左值”。 为什么?

正如@LF 和@UnholySheep 所指出的,要为Children变量设置默认值,应将其添加到成员初始化器列表中,如下所示:

Foo::Foo(const unsigned int index) : Index(index), Children(), Size(0.5/index) {}

这会将变量 Children 初始化为全 0 数组,然后可以在构造函数中进一步修改。

暂无
暂无

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

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