'?:'的返回类型(三元条件运算符) [英] Return type of '?:' (ternary conditional operator)

查看:186
本文介绍了'?:'的返回类型(三元条件运算符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么第一次返回引用?

  int x = 1; 
int y = 2;
(x> y?x:y)= 100;

第二个不是?

  int x = 1; 
long y = 2;
(x> y?x:y)= 100;

实际上,第二个根本没有编译 - 赋值左侧没有左值。 >

解决方案

表达式没有返回类型,它们有一个类型和 - 在最新的C ++标准中已知的一个值类别。 / p>

条件表达式可以是左值右值。这是它的值类别。 (这是一个简化,在 C ++ 11 我们有lvalues,xvalues和prvalues。)



在非常宽泛和简单的术语中,左值指的是存储器中的对象,并且右值只是可能不一定附加到存储器中的对象的值。



一个赋值表达式赋值给一个对象,所以被赋值的东西必须是一个值。



对于条件表达式(?:)为左值第二个和第三个操作数必须是相同类型的 lvalue 。这是因为条件表达式的类型和值类别在编译时确定,并且无论条件是否为真,都必须适当。如果其中一个操作数必须转换为不同的类型以匹配另一个,则条件表达式不能是一个值,因为该转换的结果不是一个值。。


ISO / IEC 14882:2011参考资料:



3.10 [basic.lval ] Lvalues和Rvalues(关于值类别)



5.15 [expr.cond]条件运算符(条件表达式的类型和值类别的规则)



5.17 [expr.ass]赋值和复合赋值运算符(要求赋值的lhs必须是可修改的左值)



Why does the first return a reference?

int x = 1;
int y = 2;
(x > y ? x : y) = 100;

While the second does not?

int x = 1;
long y = 2;
(x > y ? x : y) = 100;

Actually, the second did not compile at all - "not lvalue left of assignment".

解决方案

Expressions don't have return types, they have a type and - as it's known in the latest C++ 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.

ISO/IEC 14882:2011 references:

3.10 [basic.lval] Lvalues and rvalues (about value categories)

5.15 [expr.cond] Conditional operator (rules for what type and value category a conditional expression has)

5.17 [expr.ass] Assignment and compound assignment operators (requirement that the l.h.s. of an assignment must be a modifiable lvalue)

这篇关于'?:'的返回类型(三元条件运算符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆