Return ?: 运算符的类型和 C++ 入门中的措辞
Return type of ?: operator, and phrasing in C++ Primer
我读了这个 post 以大致了解从条件运算符返回的类型和值类别:Return type of '?:' (ternary conditional operator)
这几乎回答了我的问题,除了 C++ Primer 中描述同一事物的措辞让我有点困惑。
"That result of the conditional operator is an lvalue if both expressions are lvalues or if they convert to a common lvalue type. Otherwise the result is an rvalue."
加粗的部分让我很反感。这会向我建议,例如
int main(){
int y = 2;
char z = 3;
((50<60) ? y : z) = 3;
}
会很好,因为 y 和 z 都可以转换为 int(好吧,z 将是转换后的那个),它是一种左值类型(对吗?),因此条件运算符将给出一个左值作为其值类别。但是,这段代码无法编译,因为它实际上给出了一个右值。谁能提供一个粗体部分提到的例外情况的例子,这样我就可以理解它试图表达什么意思了?
我的理解好像是:如果表达式是同一类型的左值,则返回该类型的左值。否则返回一个右值(某些编译器确定的类型)。
如果 z
转换为 int
,左值到右值的转换已经应用,结果是纯右值,而不是左值。
?:
的一个示例,其中两个操作数具有不同的类型,但结果是左值,其中一个是 const
限定的而另一个不是:
const int &f(bool a, int &b, const int &c) {
// b has type int, c has type const int, the result is an lvalue of type const int
return a ? b : c;
}
另一个例子是 class 和自定义转换运算符:
struct S {
operator int&();
};
int &f(bool a, int &b, S &c) {
// b has type int, c has type S, the result is an lvalue of type int
// if a is false, c's conversion operator is called
return a ? b : c;
}
我读了这个 post 以大致了解从条件运算符返回的类型和值类别:Return type of '?:' (ternary conditional operator)
这几乎回答了我的问题,除了 C++ Primer 中描述同一事物的措辞让我有点困惑。
"That result of the conditional operator is an lvalue if both expressions are lvalues or if they convert to a common lvalue type. Otherwise the result is an rvalue."
加粗的部分让我很反感。这会向我建议,例如
int main(){
int y = 2;
char z = 3;
((50<60) ? y : z) = 3;
}
会很好,因为 y 和 z 都可以转换为 int(好吧,z 将是转换后的那个),它是一种左值类型(对吗?),因此条件运算符将给出一个左值作为其值类别。但是,这段代码无法编译,因为它实际上给出了一个右值。谁能提供一个粗体部分提到的例外情况的例子,这样我就可以理解它试图表达什么意思了?
我的理解好像是:如果表达式是同一类型的左值,则返回该类型的左值。否则返回一个右值(某些编译器确定的类型)。
如果 z
转换为 int
,左值到右值的转换已经应用,结果是纯右值,而不是左值。
?:
的一个示例,其中两个操作数具有不同的类型,但结果是左值,其中一个是 const
限定的而另一个不是:
const int &f(bool a, int &b, const int &c) {
// b has type int, c has type const int, the result is an lvalue of type const int
return a ? b : c;
}
另一个例子是 class 和自定义转换运算符:
struct S {
operator int&();
};
int &f(bool a, int &b, S &c) {
// b has type int, c has type S, the result is an lvalue of type int
// if a is false, c's conversion operator is called
return a ? b : c;
}