[英]conditional operator can return reference?
我遇到了一行代码,从未想过它可能会运行良好。 我认为条件运算符返回值并且不能与引用一起使用。
一些伪代码:
#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中,条件运算符不表示左值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.