C++ class: 必须显式初始化成员

C++ class: must explicitly initialize the member

所以,我将这个 class 命名为 'Grid'。我还有一个叫 'Field' 的 class。 Field-class 有 4 个 Grid 类型的变量,它们都在构造函数中设置。除了,它们不是......或者至少编译器不这么认为。

我不太明白为什么,我将所有变量设置为一个新实例。

当我将鼠标悬停在红色下划线(在构造函数下方)上时,它显示: "constructor for 'Field' must explicitly initialize the member 'b_attack' which does not have a default constructor"

代码:

class Grid{
    friend class Field;
private:
    unsigned int xSize;
    unsigned int ySize;
    bool *ptrfield;
    Grid(unsigned int xSize, unsigned int ySize){
        this->xSize = xSize;
        this->ySize = ySize;
        ptrfield = new bool[xSize*ySize];
    }
};

class Field{
private:
    Grid a_own;
    Grid a_attack;
    Grid b_own;
    Grid b_attack;
public:
    Field(unsigned int xSize, unsigned int ySize){
        a_own = Grid(xSize, ySize);
        a_attack = Grid(xSize, ySize);
        b_own = Grid(xSize, ySize);
        b_attack = Grid(xSize, ySize);
    }
    void print(){
        std::cout << "aHELLO" << std::flush;
        std::cout << a_own.xSize << std::flush;
    }
}; 

问题是您的 4 Grid 成员对象是在 您的 Field 构造函数的主体被输入之前创建的(或者至少,编译器想要生成代码来创建它们 - 但它不能);参见 this cppreference(加粗我的):

Before the compound statement that forms the function body of the constructor begins executing, initialization of all direct bases, virtual bases, and non-static data members is finished. Member initializer list is the place where non-default initialization of these objects can be specified. For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified. No initialization is performed for anonymous unions or variant members that do not have a member initializer.

从这个引用(关于 "members that cannot be default-initialized" 的评论)中,我们可以看到我们可以在初始化列表中提供所需的初始化; this 紧接在构造函数声明的结束 ) 之后,使用 : 后跟所需的逗号分隔的初始值设定项。像这样,在你的情况下:

    Field(unsigned int xSize, unsigned int ySize) : // The ":" starts our initializer list
        a_own(xSize, ySize),      // .. and each one of these constructs a "Grid"
        a_attack(xSize, ySize),
        b_own{ xSize, ySize },    // This "{...}" form is newer and many prefer it,
        b_attack{ xSize, ySize }  // but it can also be a bit confusing
    {
        return; // We now have nothing left to do in the actual "body" of the c'tor!
    }

请随时要求进一步澄清and/or解释。

PS:对于您发布的代码,我的编译器给出了您为所有四个 Grid 成员报告的错误;也许你的 'gives up' 在第一个之后?