条件运算符可以返回引用?

Oru*_*ner 4 c++ conditional-operator

我遇到了一行代码,从未想过它可能会运行良好.我认为条件运算符返回值并且不能与引用一起使用.

一些伪代码:

#include <iostream>

using namespace std;

class A {
public:
  A(int input) : v(input) {};
  void print() const { cout << "print: " << v  << " @ " << this << endl; }
  int v;
private:
  //A A(const A&);
  //A operator=(const A&);
};

class C {
public:
  C(int in1, int in2): a(in1), b(in2) {}
  const A& getA() { return a;}
  const A& getB() { return b;}
  A a;
  A b;
};

int main() {
  bool test = false;
  C c(1,2);
  cout << "A @ " << &(c.getA()) << endl;
  cout << "B @ " << &(c.getB()) << endl;

  (test ? c.getA() : c.getB()).print();  // its working
}
Run Code Online (Sandbox Code Playgroud)

谁能解释一下?谢谢.

Fre*_*Foo 10

你对条件运算符的假设是错误的.表达式的类型是表达式c.getA()和类型的任何类型c.getB(),如果它们具有相同的类型,并且如果它们表示左值,那么整个表达式也是如此.(确切的规则在C++标准的第5.16节中.)

你甚至可以这样做:

(condition? a: b) = value;
Run Code Online (Sandbox Code Playgroud)

有条件地设置任一abvalue.请注意,这是特定于C++的; 在C中,条件运算符不表示左值.