我了解错误消息的基本知识;提醒我,此代码可能根本不返回任何内容。但是,我不明白为什么。我的代码很完美,不是吗?
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
最佳答案
用题词注释进行更正。
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;
}
}
关于c++ - 错误: “Control may reach end of non-void function” in c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25903619/