繁体   English   中英

c++ 如何在构造函数中初始化成员数组?

[英]c++ How do I initialize a member array in a constructor?

我正在尝试在我创建的 class 的默认构造函数中初始化一个成员数组。 但是,我尝试过的任何方法都没有奏效。 我对 c++ 和一般编程很陌生,我还没有找到我在网上寻找的答案。 在 my.hpp 文件中,我有:

class thing
{
private:
    std::string array[8][8];
    
public:
    
    thing();
};

在相应的.cpp 文件中,我有:

thing::thing()
{
    array =
    {
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"}
    };
//error: Array type 'std::string [8][8]' is not assignable
} 

我还尝试了以下方法:

Board::Board()
{
    std::string array[8][8] =
    {
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"}
    };
}

这样做不会导致任何编译器错误,但它似乎并没有真正起作用。 当我尝试计算数组中的元素时,我什么也没得到。 有没有办法做我想做的事?

要么使用构造函数初始化器列表,要么使用默认成员初始化器

#include <string>

class thing {
    std::string array[8][8];

public:
    thing();
};

thing::thing()
    : array{
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
    }   
{ }

class thing2 {
    std::string array[8][8] = { 
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
        {"a", "b", "c", "d", "e", "f", "g", "h"},
    };  
};

int main() {
    thing t;
    (void)t;

    thing2 t2; 
    (void)t2;
}

暂无
暂无

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

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