問題描述
錯誤的形式:
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&"類型的非常量引用無效的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!