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"
我有一个播放器类,其中我有一个函数来返回播放器对象的尺寸和位置的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的评论吗:
简短回答:因为左值引用无法绑定右值。
相关文章:
- C++/SDL "initial value of reference to a non-const must be an lvalue"
- non-const find() in std::unordered_set
- const vs non-const变量一旦分配就没有变化
- 如何修复"initial value of reference to non-const must be an lvalue?"
- 使用 non-const 构造 const 对象
- 在C 17中,为什么关联容器具有``擦除''成员函数,该函数会采用(non-`const`)``iTerator'
- 为什么 boost::interprocess::managed_shared_ptr 到 non-const 不能转换
- "invalid initialization of non-const reference of type..." 克隆() 函数错误
- 为什么无法使用复制构造函数实例化"non const"而可以在没有复制构造函数的情况下实例化配对?
- 如何在没有重复代码的情况下实现"const"和"non-const"重载?
- 为什么在设置类成员时会自动从 const 转换为 non-const 并发生?
- C++ "invalid initialization of non-const reference"错误
- 通用成员函数定义,可从 'const' 和 'non-const' 对象实例化
- C++:"invalid initialization of non-const reference of type ‘List&’ from a temporary of type ‘List*’"
- 如何使用<double>boost::p ython通过引用将non-const std::vector传递给Python?
- 为什么要编译?期待"cannot assign a constant to a non-const reference"
- 在pass-by-const-reference方法内部的c++ pass-by-non-const-reference
- 使用模板时出现奇怪的"invalid initialization of non-const reference"
- 用于禁用"temporary to non-const reference"错误的 G++ 标志
- 引用(类型 &)"non-const lvalue reference to type cannot bind"错误,但指针(类型 *)不错误