运算符的重载
#include<iostream>using namespace std;
class Complex
{public:
Complex(double real=0,double imag=0);
friend Complex operator *(const Complex &c1,const Complex &c2);
friend Complex operator /(const Complex &c1,const Complex &c2);
friend bool operator ==(const Complex &c1 ,const Complex &c2);
friend bool operator !=(const Complex &c1,const Complex &c2);
friend ostream & operator <<(ostream &,Complex &);
friend istream & operator >>(istream &,Complex &);
void compare();
double real,imag;
};
//以上是函数声明
Complex::Complex(double r,double i):real(r),imag(i){}
Complex operator *(const Complex &c1,const Complex &c2 )
{return Complex(c1.real*c2.real-c1.imag*c2.imag,c1.imag*c2.real+c1.real*c2.imag);}
Complex operator /(const Complex &c1,const Complex &c2 )
{return Complex((c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));}
ostream & operator <<(ostream & output ,Complex &c)
{ output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl;
return output;
}
istream & operator >>(istream & input ,Complex &c)
{input>>c.real>>c.imag;
return input;
}
bool operator ==(const Complex &c1,const Complex &c2 )
{if((c1.real==c2.real)&&(c1.imag==c2.imag))
return true;
else return false;
}
bool operator !=(const Complex &c1,const Complex &c2 )
{if((c1.real!=c2.real)||(c1.imag!=c2.imag))
return true;
else return false;
}
void Complex::compare(const Complex &c1,const Complex &c2 )
{if(operator== (c1,c2)==1)
cout<<"c1==c2";
else cout<<"c1!=c2";
}
//以上是函数定义
int main()
{Complex c1,c2,c3;
cin>>c1;
cin>>c2;
cout<<"c1="<<c1;
cout<<"c2="<<c2;
c3=c1*c2;
cout<<"c3="<<c3;
c3=c1/c2;
cout<<"c3="<<c3;
c1=c2;
cout<<"c1="<<c1;
cout<<"c2="<<c2;
compare(c1,c2);
return 0;
}
//我想实现的功能是修改该类,使之能用重载的>>和<<运算符输入和输出复数;
2) 重载乘法和除法运算符,使之能执行两个复数的代数乘法和代数除法运算;
3) 重载运算符==和!=,使之能比较两个复数;
4) 重载运算符=,使之能进行两个复数的赋值运算。
程序运行后报错,说我compare函数没定义,晕啊