从对象调用成员对象,错误:引用非常量值的初始值必须是左值



我有游戏、房间、宝箱和物品栏等。

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

Room 包含 Chest 对象的向量、一个方法 addChest(将宝箱添加到宝箱向量(和一个从宝箱向量返回宝箱的方法getChest(给定索引(。

宝箱包含一个物品栏对象。

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

doSomething() 函数中,我向房间 1 添加一个宝箱,并调用 open() 函数,并将我刚刚添加的房间 1 箱子中的物品栏作为参数。

仅编写下面的代码就会给出错误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;
}

我不明白为什么会发生此错误。但是,我知道如果我在 Chest 后面添加一个& getChest()错误就会消失。

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

还有

什么其他方法可以修复它?

将打开方法的原型更改为:

void open(const Inventory &inventory)

或者将getChest方法更改为此方法,如@1201ProgramAlarm评论的那样:

Chest& getChest(int index)

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

发生此错误是因为程序员尝试执行的操作指示即将发生的逻辑错误,因为该方法需要可变的左值引用,但您传递的是临时对象。

阅读更多 为什么右值不能绑定到非常量左值引用,除了写入临时没有效果的事实?


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

无需

在代码中使用指针this。我建议你(再次(阅读this。何时应显式使用"this"指针?

最新更新