从对象调用成员对象,ERROR:对非const的引用的初始值必须是左值

问题描述 投票:2回答:1

我有游戏,房间,胸部和库存课程。

游戏包含一个Room对象和一个doSomething()函数。

房间包含一个胸部对象的矢量,一个方法addChest(它增加胸部到胸部矢量),以及一个从胸部矢量(给定索引)返回胸部的方法getChest

胸部包含一个库存对象。

还有一个open()函数,它通过引用将Inventory对象作为参数。

doSomething()函数中,我添加了一个胸部到room1并调用open()函数作为参数从我刚刚添加的room1胸部的库存。

只需编写下面的代码就会在open(this->room1.getChest(0).inventory);中出错

#include <vector>

using namespace std;

class Inventory {

};

class Chest {
public:
    Inventory inventory;
};

class Room {
    vector<Chest> chests;
public:
    Room();

    inline void addChest(Chest chest) { this->chests.push_back(chest); }
    inline Chest getChest(int index) { return this->chests[index]; }

};

class Game {
    Room room1;
public:
    void doSomething();
};

void open(Inventory &inventory) {
    //Inventory management
}

void Game::doSomething() {
    Chest chest;
    this->room1.addChest(chest);
    open(this->room1.getChest(0).inventory); //Error here: initial value of reference to non-const must be an lvalue
}

int main() {
    Game game;
    game.doSomething();

    return 0;
}

我不明白为什么会发生这种错误。但是,我知道如果我在&的胸部后添加一个getChest(),则错误消失。

原始代码有什么问题? /还有其他什么方法可以修复它?

c++ class methods pass-by-reference derived-class
1个回答
2
投票

还有哪些其他方法可以修复它?

将open方法的原型更改为:

void open(const Inventory &inventory)

或者将getChest方法更改为此,如@ 1201ProgramAlarm所述:

Chest& getChest(int index)

它将引用存储在向量中的对象。

发生错误是因为程序员尝试做的事情表明即将发生逻辑错误,因为该方法需要一个可变的左值引用,但是您传递的是临时对象。

阅读更多Why can an rvalue not bind to a non-const lvalue reference, other than the fact that writing to a temporary has no effect?


不是错误的原因,但这里有一个提示:

您不需要在代码中使用this指针。我建议你阅读关于this(再次)。 When should I make explicit use of the `this` pointer?

© www.soinside.com 2019 - 2024. All rights reserved.