'?:' 的结果类型是什么? (三元/条件运算符)?
为什么第一个条件运算符会产生引用?
int x = 1;
int y = 2;
(x > y ? x : y) = 100;
然而,第二个却没有。
int x = 1;
long y = 2;
(x > y ? x : y) = 100;
实际上,第二个根本无法编译:
错误:需要左值作为赋值的左操作数 | (x>y?x:y)=100; | ~~~~~~~^~~~~~~~
Why does the first conditional operator result in a reference?
int x = 1;
int y = 2;
(x > y ? x : y) = 100;
However, the second does not.
int x = 1;
long y = 2;
(x > y ? x : y) = 100;
Actually, the second does not compile at all:
error: lvalue required as left operand of assignment | (x > y ? x : y) = 100; | ~~~~~~~^~~~~~~~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
表达式没有返回类型,它们有一个类型和(自 C++11 标准以来众所周知的)值类别。
条件表达式可以是左值或右值。这是它的价值类别。 (这在某种程度上是一种简化,在
C++11
中,我们有左值、x值和纯右值。)用非常广泛和简单的术语来说,左值指的是内存和右值只是一个不一定附加到内存中对象的值。
赋值表达式将值分配给对象,因此被分配的对象必须是左值。
要使条件表达式 (
?:
) 成为左值(同样,用广义和简单的术语来说),第二个和第三个操作数必须是左值相同类型。这是因为条件表达式的类型和值类别是在编译时确定的,并且无论条件是否为真,都必须适当。如果其中一个操作数必须转换为不同类型以匹配另一个操作数,则条件表达式不能是左值,因为此转换的结果不会是左值。Expressions don't have return types, they have a type and - as it's known since the C++11 standard - a value category.
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.)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.
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.三元
?:
表达式的类型是其第二个和第三个参数的公共类型。如果两种类型相同,您会得到一个参考。如果它们可以相互转换,则选择一个并转换另一个(在本例中为升级)。由于您无法返回对临时变量(转换/提升的变量)的左值引用,因此它的类型是值类型。The type of the ternary
?:
expression is the common type of its second and third argument. If both types are the same, you get a reference back. If they are convertable to each other, one gets chosen and the other gets converted (promoted in this case). Since you can't return an lvalue reference to a temporary (the converted / promoted variable), its type is a value type.它不能返回左值,因为它必须隐式提升
x
的类型以匹配y
的类型(因为x
的两边>: 不是同一类型),并且必须创建一个临时的。标准怎么说? (n1905)
表达式5.17 赋值和复合赋值运算符
It cannot return a lvalue since it will have to implicitly promote the type of
x
to match the type ofy
(since both sides of:
are not of the same type), and with that it has to create a temporary.What does the standard say? (n1905)
Expressions 5.17 Assignment and compound assignment operators
再举一个例子
One more example