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)
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |