c++ - 错误: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’

标签 c++ pointers inheritance error-handling reference

当我尝试编译程序时,我的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()行应返回Runner.cc中所示的Position数据类型,并且该参数要求使用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()返回Position副本。如果您希望update()中的更改影响tortoisePosition成员,则需要getCurrPos()通过引用返回其Position

Position Runner::getCurrPos() { 
应该成为
Position& Runner::getCurrPos() { 
有关更多信息,您可以在What is a reference variable in C++?上阅读

关于c++ - 错误: cannot bind non-const lvalue reference of type ‘Position&’ to an rvalue of type ‘Position’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64920265/

相关文章:

c++ - 在 C++ 中使用指针访问和操作数组

c++ - 遍历指向类的指针 vector

c++ - 从基类方法使用派生类数据成员

c++ - 为模板参数中的每种类型声明和实现重载虚函数

c++ - 如何在可变参数包中找到 "min"类型?

c++ - 在抛出 'std::out_of_range' what(): basic_string::substr 实例后终止调用

c - 将指针传递给 C 中的函数

java - Hibernate继承

c++ - 检测到内存泄漏

C++ 继承 - 为什么调用父方法?