error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’

error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’

当我尝试编译我的程序时,我的 Race.cc 文件有错误。

 error: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’
 view.update(tortoise->getCurrPos(), tortoise->getCurrPos(), tortoise->getAvatar());
             ~~~~~~~~~~~~~~~~~~~~^~

我正在努力弄清楚如何解决这些问题,希望得到一些帮助。我不知道为什么从 View.cc 调用 update(Position&, Position&, char) 只会在第一个参数上出错,而​​在第二个参数上不会出错,因为我输入的是完全相同的东西。 tortoise->getCurrPos() 行应该 return 一个 Position 数据类型,如 Runner.cc 所示,参数要求一个 Position 类型,所以我不明白为什么它不起作用。

Race.cc

Race::Race(){ 
    Runner* tortoise = new Runner("Tortoise", 'T', 100, 1);
  
    view.update(tortoise->getCurrPos(), tortoise->getCurrPos(), tortoise->getAvatar());
}

View.cc

void update(Position& oldPos, Position& newPos, char avatar){
}

您的 update() 正在寻求通过引用获取 Position 以便它可以进行修改并将它们渗透回您传递的对象。但是,tortoise->getCurrPos()return是Positioncopy。如果您希望 update() 中的更改影响您的 tortoisePosition 成员,您需要 getCurrPos() return 其 Position通过参考。

Position Runner::getCurrPos() { 

应该变成

Position& Runner::getCurrPos() { 

有关更多信息,您可以在 What is a reference variable in C++?

上阅读