【问题标题】:Error: "Control may reach end of non-void function" in c++错误:C++ 中的“控件可能到达非 void 函数的末尾”
【发布时间】:2014-09-18 03:16:49
【问题描述】:

我了解错误消息的基本信息;它提醒我,这段代码可能根本不会返回任何东西。但是,我不明白为什么。我的代码很完美,不是吗?

rational operator / (const rational &lhs, const rational &rhs)
{
if(rhs.numerator() != 0)
{
    int numerator = lhs.numerator() * rhs.denominator();
    int denominator = lhs.denominator() * rhs.numerator();
    rational quotient(numerator, denominator);
    return quotient;
}
else cout << "error" << endl;
}   //this is where error is occurring 

【问题讨论】:

  • "控制到达非空函数的末尾[没有在所有执行路径上返回值]"
  • 您缺少return 声明。 “我的代码很完美,不是吗?” 离...

标签: c++ function compiler-errors


【解决方案1】:

用刻有 cmets 的修正。

rational operator / (const rational &lhs, const rational &rhs)
{
  if(rhs.denominator() != 0) {
    int numerator = lhs.numerator() * rhs.denominator() + 
                    rhs.numerator() * lhs.denominator();
    int denominator = lhs.denominator() * rhs.denominator();
    rational quotient(numerator, denominator);
    return quotient;
  }
  else {
   // what should be returned?
   // let's return lhs, as caller is expecting something, lhs is better than nothing
   // ideally should raise exception, and program shopuld not continue further
   cout << "error" << endl; 
   return lhs; 
  }
}

【讨论】:

【解决方案2】:

所以它很简单,你的函数需要返回一个类型rational。如果失败:

if(rhs.numerator() != 0) 

那么您将不会返回该类型的任何内容。因此发出警告。

【讨论】:

  • 所以我不能返回任何类型的错误信息?如果没有适合这种情况的理性类型怎么办?
  • @MattC。那么你应该考虑抛出一个异常。
  • @MattC.:你定义你的函数返回一个rational,所以它必须返回一个rational——或者抛出一个异常。或者您可以更改返回类型,以便它始终可以返回一个合理的值。
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
相关资源
最近更新 更多