【问题标题】:Conditional assignment for const reference objects in C++C++ 中 const 引用对象的条件赋值
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 或者:const A &reward = (score > 5 ? foo1 : foo2)();
  • @melpomene: 但不支持cond ? foo1(42) : foo2("Hi") 的大小写。
【解决方案2】:

您可以使用conditional operator 来发挥您的优势。但是,您不能使用A& reward = ...,因为foo1()foo2() 都返回const A&。您必须使用const A& reward = ...

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

【讨论】:

  • @R Sahu 感谢您的指出。我已经编辑了我的问题,将 const 包含在赋值操作中!
【解决方案3】:

作为替代方案,您可以创建额外的重载:

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

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

【讨论】:

  • 为什么要使用所有 CPS?如果你要引入一个额外的功能,为什么不直接const A &foo4(int score) { if (score > 5) return foo1(); else return foo2(); } ... void foo3(int score) { const A &reward = foo4(score); ... }
  • @melpomene:确实也有可能。取决于我们如何拆分/公开代码。
  • @Jarod42 @melpomene 当我们有很长的if-else if-else 链时,您在此处介绍的两种解决方案都非常有用。在这种情况下使用条件运算符肯定会使代码变得丑陋。感谢您的投入!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-15
  • 2013-11-24
  • 2013-12-07
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多