三目运算符可以返回引用类型,当返回的候选表达式中有一个是右值时,则返回非引用类型。
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int a = 3;
int b = 2;
// 1.
// 三目运算符返回引用
(a > b ? a : b) = 4;
cout << "a = " << a << " b = " << b <<endl; // 输出: a = 4 b = 2
// 2.
// 三目运算符返回右值
// error: lvalue required as left operand of assignment
(a < b ? a + 1 : b) = 4;
// 下面的decltype返回 int
decltype(a ? a + 1 : a) ri;
// 下面的decltype返回 int&
// error: 'r' declared as reference but not initialized
decltype(a?a:a) r;
}