先帖一个课堂作业,运算符重载、友元函数:
#include <iostream.h>
class Complex
{
private:
double rel,img;
public:
Complex(double r=0,double i=0)
{
rel=r;
img=i;
}
void show(void)
{
cout<<rel;
if(img>=0)cout<<"+";
if(img)cout<<img<<"i";
cout<<endl;
};
friend Complex operator+(Complex &c1,Complex &c2);
friend Complex operator-(Complex &c1,Complex &c2);
friend Complex operator*(Complex &c1,Complex &c2);
friend Complex operator/(Complex &c1,Complex &c2);
};
Complex operator+(Complex &c1,Complex &c2)
{
Complex c;
c.rel = c1.rel+c2.rel;
c.img = c1.img+c2.img;
return c;
}
Complex operator-(Complex &c1,Complex &c2)
{
Complex c;
c.rel = c1.rel-c2.rel;
c.img = c1.img-c2.img;
return c;
}
Complex operator*(Complex &c1,Complex &c2)
{
Complex c;
c.rel = c1.rel*c2.rel-c1.img*c2.img;
c.img = c1.img*c2.rel+c1.rel*c2.img;
return c;
}
Complex operator/(Complex &c1,Complex &c2)
{
Complex c;
double temp;
temp=c2.rel*c2.rel+c2.img*c2.img;
if(temp)
{
c.rel = (c1.rel*c2.rel+c1.img*c2.img)/temp;
c.img = (c1.img*c2.rel-c1.rel*c2.img)/temp;
}
return c;
}
int main(int argc,int *argv[])
{
Complex c1(1,2);
Complex c2(3,4);
Complex c3(0,0);
c3=c1+c2;
cout<<"c1+c2=";
c3.show();
c3=c1-c2;
cout<<"c1-c2=";
c3.show();
c3=c1*c2;
cout<<"c1*c2=";
c3.show();
c3=c1/c2;
cout<<"c1/c2=";
c3.show();
return 0;
}