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"
我有一个播放器 class,其中我有一个函数 return 一个 SDL_Rect 用于我的播放器对象的尺寸和位置:
SDL_Rect Player::pos()
{
return SDL_Rect { mPosX, mPosY, PLAYER_WIDTH, PLAYER_HEIGHT };
}
当我在我的主程序中使用它来渲染播放器时:
Renderer::Draw(img, player.pos(), NULL, angle);
我收到错误:"initial value of reference to a non-const must be an lvalue"
但是当我改为写:
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 的评论:
Short answer: Because lvalue references cannot bind rvalues.
我有一个播放器 class,其中我有一个函数 return 一个 SDL_Rect 用于我的播放器对象的尺寸和位置:
SDL_Rect Player::pos()
{
return SDL_Rect { mPosX, mPosY, PLAYER_WIDTH, PLAYER_HEIGHT };
}
当我在我的主程序中使用它来渲染播放器时:
Renderer::Draw(img, player.pos(), NULL, angle);
我收到错误:"initial value of reference to a non-const must be an lvalue" 但是当我改为写:
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 的评论:
Short answer: Because lvalue references cannot bind rvalues.