我遇到了一行代码,但从未想过它会运行良好。我认为条件运算符的返回值不适用于引用。
一些伪代码:
#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
}
谁能解释一下?谢谢。
最佳答案
您对条件运算符的假设是错误的。表达式的类型是表达式 c.getA()
和 c.getB()
具有的任何类型,如果它们具有相同的类型,并且如果它们表示左值,那么整个表达式也是如此。 (具体规则在 C++ 标准的 §5.16 中。)
你甚至可以这样做:
(condition? a: b) = value;
有条件地将 a
或 b
设置为 value
。请注意,这是特定于 C++ 的;在 C 中,条件运算符不表示左值。
关于c++ - 条件运算符可以返回引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14233852/