当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Constructor initialization error

问题描述:

I'm creating a simple card game foundation and now I'm working on the class that creates objects that represent each player. There seems to be a problem with the constructor though: Constructor for 'Spelare' must explicitly initialize the reference member '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?

};

网友答案:

Change your constructor to:

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

The problem is that a reference cannot be re-assigned once it has been declared and initialised. Your constructor attempts to declare but not initialise the reference, and then assign to it - which fails.

You need to initialise the reference via the constructor's initialisation list. You also need to do the same for dator, since it's const - but it's just good practice in general.

网友答案:

References and const members must be initialized like this:

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

However, having a reference as a class member burned me a few times, so I advise against it.

网友答案:

Try this:

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

    // ...
};

So the trick is to initialize leken in an initializer list. This has to be done because it is a reference (mind the & in its declaration). And a reference declared in a class simply must be initialized this way.

Finally since dator is a const and cannot be assigned neither it has to be initialized in the initializer list, too.

网友答案:

Initialization of class members is not performed inside the ctor body. When entering the ctor body all member variables have already been initialized, so assignment is instead performed.

Initialization of class members is usually performed using an initialization list.

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.
};

As a refererence must be initialized to point to some data and it can not be reassigned to later point to some other data, the following is an error.

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_;
};

Also const members can not be assigned to (naturally), they must be initialized to some value.

分享给朋友:
您可能感兴趣的文章:
随机阅读: