2013-01-09 74 views
4

我遇到了一行代碼,從來沒有想過它可能會很好。我認爲條件運算符返回值並不適用於引用。有條件的運算符可以返回引用嗎?

一些僞代碼:

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

有人能解釋一下嗎?謝謝。

回答

10

你對條件運算符的假設是錯誤的。表達式的類型是表達式c.getA()c.getB()所具有的任何類型,如果它們具有相同的類型,並且它們表示左值,那麼整個表達式也是如此。 (確切的規則是在C++標準的§5.16)

你甚至可以做到這一點:

(condition? a: b) = value; 

有條件地設置或者abvalue。請注意,這是C++特有的;在C中,條件運算符不表示左值。