'?:' 的返回类型(三元条件运算符)
为什么第一个返回一个引用?
Why does the first return a reference?
int x = 1;
int y = 2;
(x > y ? x : y) = 100;
虽然第二个没有?
int x = 1;
long y = 2;
(x > y ? x : y) = 100;
实际上,第二个根本没有编译 - 不是左值赋值".
Actually, the second did not compile at all - "not lvalue left of assignment".
推荐答案
表达式没有返回类型,它们有一个类型和 - 正如最新的 C++ 标准中所知 - 一个值类别.
Expressions don't have return types, they have a type and - as it's known in the latest C++ standard - a value category.
条件表达式可以是 lvalue 或 rvalue.这是它的价值类别.(这有点简化,在 C++11
中,我们有左值、x 值和右值.)
A conditional expression can be an lvalue or an rvalue. This is its value category. (This is somewhat of a simplification, in C++11
we have lvalues, xvalues and prvalues.)
用非常广泛和简单的术语来说,lvalue 指的是内存中的一个对象,而 rvalue 只是一个不一定附加到内存中的对象的值.
In very broad and simple terms, an lvalue refers to an object in memory and an rvalue is just a value that may not necessarily be attached to an object in memory.
赋值表达式为对象赋值,因此被赋值的事物必须是一个左值.
An assignment expression assigns a value to an object so the thing being assigned to must be an lvalue.
要使条件表达式 (?:
) 成为左值(同样,广义和简单而言),第二个和第三个操作数必须是 相同类型的左值.这是因为条件表达式的类型和值类别是在编译时确定的,并且无论条件是否为真,都必须是合适的.如果必须将其中一个操作数转换为不同的类型以匹配另一个,则条件表达式不能是 lvalue,因为此转换的结果将不是 lvalue.
For a conditional expression (?:
) to be an lvalue (again, in broad and simple terms), the second and third operands must be lvalues of the same type. This is because the type and value category of a conditional expression is determined at compile time and must be appropriate whether or not the condition is true. If one of the operands must be converted to a different type to match the other then the conditional expression cannot be an lvalue as the result of this conversion would not be an lvalue.
ISO/IEC 14882:2011 参考:
ISO/IEC 14882:2011 references:
3.10 [basic.lval] 左值和右值(关于值类别)
3.10 [basic.lval] Lvalues and rvalues (about value categories)
5.15 [expr.cond] 条件运算符(条件表达式的类型和值类别的规则)
5.15 [expr.cond] Conditional operator (rules for what type and value category a conditional expression has)
5.17 [expr.ass] 赋值和复合赋值运算符(要求赋值的 l.h.s. 必须是可修改的左值)
5.17 [expr.ass] Assignment and compound assignment operators (requirement that the l.h.s. of an assignment must be a modifiable lvalue)
相关文章