构造函数初始化错误

Constructor initialization error

本文关键字:错误 初始化 构造函数      更新时间:2023-10-16

我正在创建一个简单的卡牌游戏基础,现在我正在制作创建代表每个玩家的对象的类。构造函数似乎有一个问题: 'Spelare'的构造函数必须显式初始化引用成员'leken'

class Spelare {
public:
    Spelare(Kortbunt& kortlek, bool ar_dator) {leken = kortlek; dator = ar_dator;} //Constructor
    int spela();
private:
    Kortbunt hand; //The cards in the players hand
    Kortbunt& leken; //The cards on the table
    const bool dator; //Is this player a computer?
};

将构造函数更改为:

Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {} 

问题是引用一旦被声明和初始化就不能被重新赋值。构造函数试图声明但不初始化引用,然后对其进行赋值——这将失败。

你需要通过构造函数的初始化列表初始化引用。您还需要对dator执行相同的操作,因为它是const -但这只是一般的良好实践。

引用和const成员必须这样初始化:

Spelare(Kortbunt& kortlek, bool ar_dator) : leken(kortlek), dator(ar_dator) {} 

然而,把引用作为类成员让我很痛苦,所以我建议不要这样做。

试试这个:

class Spelare {
public:
    Spelare(Kortbunt& kortlek, bool ar_dator)
        : leken(kortlek), dator(ar_dator)
    {}
    // ...
};
所以技巧是在初始化列表中初始化leken。必须这样做,因为它是一个引用(注意其声明中的&)。在类中声明的引用也必须这样初始化。

最后,由于dator是const,不能赋值,因此也必须在初始化列表中初始化。

类成员的初始化是而不是在actor主体内进行的。当进入函数体时,所有的成员变量都已经初始化了,所以要执行赋值

类成员的初始化通常使用初始化列表执行。

struct Foo {
    Foo(int a, int b, int c)
        : a{a}, b{b}, c{c} // Initialization list.
    {
        /* ctor body */
    }
    int a;
    int b;
    const int c;
    std::string s{"Test"}; // C++11 also allows non-const in class initialization.
};

由于引用必须初始化,指向某些数据,并且可以重新赋值,稍后指向其他一些数据,下面是一个错误。

struct Bar {
    Bar(Foo& f) // Error: uninitialized reference member.
    {
        f_ = f; // If f_ had been initialized this is assignment to where f_ points,
                // not reassignment of what data f_ is a reference to.
    }
    Foo& f_;
};

const成员也不能赋值(自然),它们必须初始化为某个值