c++运算符重载问题
#include <iostream>#include <cmath>
using namespace std;
class Complex
{
public:
Complex();
Complex(double r);
Complex(double r,double i);
void display();
friend Complex operator+(Complex &c1,Complex &c2);
private:
double real;
double imag;
};
Complex::Complex()
{
real=0;
imag=0;
}
Complex::Complex(double r)
{
real=r;
imag=0;
}
Complex::Complex(double r,double i)
{
real=r;
imag=i;
}
Complex operator+(Complex &c1,Complex &c2)
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
void Complex::display()
{
if(imag>0)
cout<<"("<<real<<"+"<<imag<<"i)"<<endl;
else if(imag==0)
cout<<"("<<real<<")"<<endl;
else
cout<<"("<<real<<"-"<<fabs(imag)<<"i)"<<endl;
}
int main()
{
Complex c1(2,1),c;
c=c1+2.5; // 把这行注释掉能编译通过,编译器报错说我的重载+函数有问题。但是我没找出来。还请各位指教。
cout<<"c1+2.5=";
c.display();
return 0;
}