简体   繁体   中英

conditional operator can return reference?

I came across a line of code and never thought it might work well. I thought the conditional operator return value and does not work with reference.

Some pseudo code:

#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
}

Can someone explain? Thx.

Your assumption about the conditional operator is wrong. The type of the expression is whatever type the expressions c.getA() and c.getB() have, if they have the same type, and if they denote lvalues, then so does the entire expression. (The exact rules are in §5.16 of the C++ standard.)

You can even do this:

(condition? a: b) = value;

to conditionally set either a or b to value . Note that this is C++-specific; in C, the conditional operator does not denote an lvalue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM