c++的运算符重载中涉及的精度检查问题

来源:百度知道 编辑:UC知道 时间:2024/06/14 21:29:04
//实数计算类的运算符重载

#include<iostream.h>
#include<stdlib.h>
#include<math.h>

class Real
{
public:
Real(int a=0){ value=a; }
friend Real operator+(const Real & i1,const Real & i2);
friend Real operator-(const Real & i1,const Real & i2);
friend Real operator*(const Real & i1,const Real & i2);
friend Real operator/(const Real & i1,const Real & i2);
double GetValue()const;
private:
double value;

};

Real operator+(const Real & i1,const Real & i2) //重载加法运算符
{

double temp=i1.value+i2.value;
if( temp<3.4e38 && temp>-3.4e38) return Real(temp);
else
{ cout<<"\nData overflow!\n"<<endl; //溢出处理--退出程序
abort();
}

}
double Real::GetValue()const
{ return value; }

lz不够细心,Real的构造函数参数是int的,溢出int了

应该在这一句之前,检查溢出的,因为有可能传进来的参数就溢出了,你不检查,编译器当然要帮你检查了,所以就会出现异常
double temp=i1.value+i2.value;