gpt4 book ai didi

c++ - 返回类型 '?:'(三元条件运算符)

转载 作者:IT老高 更新时间:2023-10-28 11:27:12 31 4
gpt4 key购买 nike

为什么第一个返回引用?

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

而第二个没有?

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

实际上,第二个根本没有编译——“not lvalue left of assignment”。

最佳答案

表达式没有返回类型,它们有一个类型和 - 正如最新的 C++ 标准中所知道的 - 一个值类别。

条件表达式可以是左值右值。这是它的值(value)范畴。 (这有点简化,在 C++11 中我们有左值、xvalue 和 prvalue。)

在非常广泛和简单的术语中,lvalue 是指内存中的对象,而 rvalue 只是一个可能不一定附加到内存中的对象的值.

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

要使条件表达式 (?:) 成为 左值(同样,广义和简单的术语),第二个和第三个操作数必须是 <同类型的 em>左值。这是因为条件表达式的类型和值类别是在编译时确定的,并且无论条件是否为真都必须是适当的。如果必须将其中一个操作数转换为不同的类型以匹配另一个,则条件表达式不能是 lvalue,因为此转换的结果不会是 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)

关于c++ - 返回类型 '?:'(三元条件运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535226/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com