【发布时间】:2018-08-27 16:16:38
【问题描述】:
这是一个说明我的问题的代码 sn-p:
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.
}
如何在 if else 块之后访问 foo3() 中的 reward 对象?这是避免代码重复所必需的。
提前致谢!
【问题讨论】:
-
A& reward{condition ? foo1() : foo2()}; -
使用条件运算符。
标签: c++ ternary-operator const-reference