Pergunta

When I try to write a one line with a chain of methods as shown below, I get a compilation error:

int index=data.getPlayer1().getIndex();

The error in this case is

Invalid arguments

But when I divide the chain, everything works out fine:

Player player1=data.getPlayer1();
int index=player1.getIndex();

All of these methods are part of the same namespace and the #include notations are in order. How can I solve this issue?

Edit:

The getters are shown below:

    const Player& getPlayer1() const {
    return player1;
}

int getIndex() { return index;}
Foi útil?

Solução

getPlayer() returns a const Player& but getIndex() is a non-const member function and it is illegal to call a non-const member function on a const object. Make getIndex() const (as it should be anyway as it is a getter and does not modify the object):

int getIndex() const { return index; }
             //^^^^^

It works in the split case:

Player player1=data.getPlayer1();

because of copy of Player is being made, and player1 is not a const object and getIndex() can be invoked.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top