c++ - 条件运算符可以返回引用吗?

标签 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
}

谁能解释一下?谢谢。

最佳答案

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

你甚至可以这样做:

(condition? a: b) = value;

有条件地将 ab 设置为 value。请注意,这是特定于 C++ 的;在 C 中,条件运算符不表示左值。

关于c++ - 条件运算符可以返回引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14233852/

相关文章:

c++ - C++ 中的函数引用和 assert(0)

c++ - 套接字编程中非法查找的可能原因

c++ - STL 或 BOOST 是否提供任何干净的方法来获取排序顺序而无需重新排序原始序列?

php - 这个语法是什么 ( page = $page ? $page : 'default' ) in PHP mean?

javascript - 了解 java/apex 复杂三元运算符

c++ - boost::bind 如何与提供的签名不匹配但工作正常?

c++ - Delphi 和 C/C++ DLL

带数组赋值的 Powershell 5.1 三元

c - 为什么三元运算可能未定义

java - 三元运算符