c++ - 错误 : control Reaches end of non void function

标签 c++ compiler-errors return numerical-methods

我正在学习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"**

最佳答案

operator<<被定义为返回 std::ostream& :

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. [...]

关于c++ - 错误 : control Reaches end of non void function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21978188/

相关文章:

python - 从函数返回给出 None

c++ - 如何使用双参数或无参数执行 C++ 函数

c++ - 如何让日志更容易维护?

尝试抛出异常时出现c++模板化函数错误

compiler-errors - 编译cydia时出现错误1

c# - 谁在 C# 中调用 Main() 方法? Main()方法异常时如何退出应用程序?

c++ - nVidia 推力 : device_ptr Const-Correctness

c++ - 斧头错误 : You cannot access the cpp package while targeting cross (for cpp. 库)

java - 运行 zxing 的单元测试失败

java - 我如何仅根据方法名称知道方法返回类型?