我正在学习 C ++ ,我从教科书中复制了这段代码,在编译代码时,最后会出现错误。错误说:
Control达到非空函数的结束
并且它位于代码的末尾:
#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"**
答案 0 :(得分:1)
好operator<<
定义为返回std::ostream&
:
std::ostream& operator<<(std::ostream& output, const ComplexNumber& z)
^^^^^^^^^^^^^
但你没有return语句,这是undefined behavior并且意味着你不能依赖程序的行为,结果是不可预测的。看起来你应该有:
return output ;
在功能结束时。我们可以从草案C ++标准部分6.6.3
看到这是未定义的行为。返回声明第2段说:
[...]离开函数末尾相当于没有值的返回;这会导致值返回函数中的未定义行为。 [...]
答案 1 :(得分:1)
该函数声称返回一些内容:
std::ostream& operator<<(std::ostream& output, const ComplexNumber& z)
^^^^^^^^^^^^^
但最后没有return
语句。你应该添加一个:
return output;
答案 2 :(得分:0)
此功能
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)";
}
}
返回类型std::ostream &
但是它什么都不返回。我认为有一个错字应该有
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)";
}
return output;
}