简体   繁体   中英

Conditional assignment for const reference objects in C++

Here is a code snippet that illustrates my problem :

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.

}

How can I access the reward object in foo3() after the if else block? This is required to avoid code duplication .

Thanks in advance !

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

const A &reward = (score > 5) ? foo1() : foo2();

You can use the conditional operator to your advantage. However, you may not use A& reward = ... since both foo1() and foo2() return const A& . You will have to use const A& reward = ... .

const A& reward = ( (score > 5) ? foo1() : foo2() );

As alternative, you may create additional overload:

void foo3(const A& reward)
{
    // ...
}

void foo3(int score) {
    if (score > 5)
        foo3(foo1());
    else 
        foo3(foo2());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM