C++中const引用对象的条件赋值

Swa*_*oop 0 c++ ternary-operator const-reference

这是一个说明我的问题的代码片段:

class A {...};
const A& foo1() {...}
const A& foo2() {...}

void foo3(int score) {
  if (score > 5)
    const A &reward = foo1();
  else 
    const A &reward = foo2();

  ...

  // The 'reward' object is undefined here as it's scope ends within the respective if and else blocks.

}
Run Code Online (Sandbox Code Playgroud)

如何在 if else 块之后访问reward对象foo3()?这是避免代码重复所必需的。

提前致谢 !

小智 5

您可以使用三元运算符:https : //en.wikipedia.org/wiki/%3F%3A

const A &reward = (score > 5) ? foo1() : foo2();
Run Code Online (Sandbox Code Playgroud)

  • 或者:`const A &reward = (score > 5 ? foo1 : foo2)();` (2认同)
  • @melpomene:但不支持大小写为 `cond ?foo1(42) : foo2("嗨")`。 (2认同)