c – 错误:控制达到非空函数的结束

我正在学习C,我从教科书中复制了这段代码,在编译代码时,最后会出现错误.错误说:

Control Reaches end of non-void function

它位于代码的末尾:

#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"**

最佳答案 井操作符<

std::ostream& operator<<(std::ostream& output, const ComplexNumber& z)
^^^^^^^^^^^^^

但是你没有返回语句,这是undefined behavior并且意味着你不能依赖程序的行为,结果是不可预测的.看起来你应该有:

return output ;

在功能的最后.我们可以从草案C标准第6.6.3节中看到这是未定义的行为.返回声明第2段说:

[…] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function. […]

点赞