C++ 中 const 引用对象的条件赋值
Conditional assignment for const reference objects in C++
这是一个说明我的问题的代码片段:
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
对象?这是 避免代码重复所必需的 。
提前致谢!
您可以使用三元运算符:https://en.wikipedia.org/wiki/%3F%3A
const A &reward = (score > 5) ? foo1() : foo2();
您可以利用 conditional operator 发挥自己的优势。但是,您不能使用 A& reward = ...
,因为 foo1()
和 foo2()
return const A&
。您将不得不使用 const A& reward = ...
.
const A& reward = ( (score > 5) ? foo1() : foo2() );
作为替代方案,您可以创建额外的重载:
void foo3(const A& reward)
{
// ...
}
void foo3(int score) {
if (score > 5)
foo3(foo1());
else
foo3(foo2());
}
这是一个说明我的问题的代码片段:
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
对象?这是 避免代码重复所必需的 。
提前致谢!
您可以使用三元运算符:https://en.wikipedia.org/wiki/%3F%3A
const A &reward = (score > 5) ? foo1() : foo2();
您可以利用 conditional operator 发挥自己的优势。但是,您不能使用 A& reward = ...
,因为 foo1()
和 foo2()
return const A&
。您将不得不使用 const A& reward = ...
.
const A& reward = ( (score > 5) ? foo1() : foo2() );
作为替代方案,您可以创建额外的重载:
void foo3(const A& reward)
{
// ...
}
void foo3(int score) {
if (score > 5)
foo3(foo1());
else
foo3(foo2());
}