error: invalid initialization of non-const reference of type ‘intamp;’ from an rvalue of type ‘int’(错误:从“int类型的右值初始化“intamp;类型的非常量引用无效)
问题描述
错误的形式:
int &z = 12;
正确形式:
int y;
int &r = y;
问题:
为什么第一个代码是错误的?标题中错误的含义"是什么?
推荐答案
C++03 3.10/1 说:每个表达式要么是左值,要么是右值."重要的是要记住,左值与右值是表达式的属性,而不是对象的属性.
C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.
左值命名对象超出单个表达式.例如, obj 、 *ptr 、 ptr[index] 和 ++x 都是左值.
Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.
右值是在它们所在的完整表达式的末尾(在分号处")消失的临时变量.例如, 1729 、 x + y 、 std::string("meow") 和 x++ 是所有右值.
Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.
address-of 运算符要求其操作数应为左值".如果我们可以取一个表达式的地址,那么这个表达式就是一个左值,否则就是一个右值.
The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.
&obj; // valid
&12; //invalid
这篇关于错误:从“int"类型的右值初始化“int&"类型的非常量引用无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:错误:从“int"类型的右值初始化“int&
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
