C++/SDL "initial value of reference to a non-const must be an lvalue"

C++/SDL "initial value of reference to a non-const must be an lvalue"

本文关键字:non-const must be an to lvalue reference SDL initial value of      更新时间:2023-10-16

我有一个播放器类,其中我有一个函数来返回播放器对象的尺寸和位置的SDL_Rect:

SDL_Rect Player::pos() 
{
return SDL_Rect { mPosX, mPosY, PLAYER_WIDTH, PLAYER_HEIGHT };
}

当我在我的主程序中使用它来渲染播放器时:

Renderer::Draw(img, player.pos(), NULL, angle);

我收到错误:"对非常量引用的初始值必须是左值" 但是当我改为写:

SDL_Rect pos = player.pos();
Renderer::Draw(img, pos, NULL, angle);

它有效。 为什么我不能直接使用 player.pos(( 而必须使用另一个 SLD_Rect 变量?

Renderer::Draw声明修改其第二个参数(否则它将是const,您不会收到该错误(,如果您传递临时参数,则修改参数毫无意义,并且很可能是一个错误,这就是禁止的原因。

请考虑以下示例:

int foo() { return 3; }
void bar(int& x) { ++x; }
void moo(const int& x) {}
int main() {
bar(foo()); // not allowed
moo(foo()); // ok     
int x = foo(); 
bar(x);     // ok, modifies x
}

如果允许bar(foo()),就不会发生任何超级糟糕的事情。另一方面,没有理由允许它。bar明确声明它想要修改其参数,那么当您无法观察到该修改时,为什么要允许传递某些内容呢?

PS:如果你觉得这个回答太过手足无措,我可以参考@DanielLangr的评论吗:

简短回答:因为左值引用无法绑定右值。

相关文章: