错误:控件已到达非无效函数的末尾
我正在学习C++,我从课本上复制了这段代码,在编译代码的时候,最后出现了一个错误。错误显示:
控件到达非void函数末尾
,位于代码末尾:
#include "ComplexNumber.hpp"
#include <cmath>
ComplexNumber::ComplexNumber()
{
mRealPart = 0.0;
mImaginaryPart = 0.0;
}
ComplexNumber::ComplexNumber(double x, double y)
{
mRealPart = x;
mImaginaryPart = y;
}
double ComplexNumber::CalculateModulus() const
{
return sqrt(mRealPart*mRealPart+
mImaginaryPart*mImaginaryPart);
}
double ComplexNumber::CalculateArgument() const
{
return atan2(mImaginaryPart, mRealPart);
}
ComplexNumber ComplexNumber::CalculatePower(double n) const
{
double modulus = CalculateModulus();
double argument = CalculateArgument();
double mod_of_result = pow(modulus, n);
double arg_of_result = argument*n;
double real_part = mod_of_result*cos(arg_of_result);
double imag_part = mod_of_result*sin(arg_of_result);
ComplexNumber z(real_part, imag_part);
return z;
}
ComplexNumber& ComplexNumber::operator=(const ComplexNumber& z)
{
mRealPart = z.mRealPart;
mImaginaryPart = z.mImaginaryPart;
return *this;
}
ComplexNumber ComplexNumber::operator-() const
{
ComplexNumber w;
w.mRealPart = -mRealPart;
w.mImaginaryPart = -mImaginaryPart;
return w;
}
ComplexNumber ComplexNumber::operator+(const ComplexNumber& z) const
{
ComplexNumber w;
w.mRealPart = mRealPart + z.mRealPart;
w.mImaginaryPart = mImaginaryPart + z.mImaginaryPart;
return w;
}
std::ostream& operator<<(std::ostream& output,
const ComplexNumber& z)
{
output << "(" << z.mRealPart << " ";
if (z.mImaginaryPart >= 0.0)
{
output << " + " << z.mImaginaryPart << "i)";
}
else
{
output << "- " << -z.mImaginaryPart << "i)";
}
} //-------->>>>**"Control Reaches end of non-void function"**
解决方案
Welloperator<<
定义为返回std::ostream&
:
std::ostream& operator<<(std::ostream& output, const ComplexNumber& z)
^^^^^^^^^^^^^
但是您没有返回语句,这是undefined behavior,这意味着您不能依赖程序的行为,结果是不可预测的。看起来您应该:
return output ;
在函数的末尾。我们可以从C++标准草案6.6.3
返回语句第2段中看到这是未定义的行为:
[.]从函数末尾流出等同于没有值的返回;这会导致值返回函数中的未定义行为。[.]
相关文章