当我尝试编译程序时,我的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.ccvoid update(Position& oldPos, Position& newPos, char avatar){
}
最佳答案
您的update()
希望通过引用获取Position
,以便它可以进行修改并将其渗透回您要传递的对象。但是,tortoise->getCurrPos()
返回Position
副本。如果您希望update()
中的更改影响tortoise
的Position
成员,则需要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/