//Complex.cpp
#include<iostream.h>
//using namespace std;当调用了友元函数时,在VC++6.0里只能用#include<iostream.h>
class Complex
{
public:
Complex(){real=0;imag=0;}//构造函数
Complex(double r){real=r;imag=0;}//转换构造函数 将double型转成Complex类型
Complex(double r,double i){real=r;imag=i;}
//operator double(){return real;}//转换类型函数 将Complex类类型(自定义类型)转换成double型,
(标准类型)
void display();
friend Complex operator+(Complex &,Complex &);//运算符重载的友元函数.
friend Complex operator-(Complex&,Complex&);
friend Complex operator*(Complex&,Complex&);
friend Complex operator/(Complex&,Complex&);
friend istream& operator>>(istream&,Complex&);
friend ostream& operator<<(ostream&,Complex&);
private:
double real;
double imag;
};
void Complex::display ()
{
cout<<"("<<real<<",";
cout<<imag<<"i)"<<endl;
}
Complex operator+(Complex &c1,Complex &c2)
{
return Complex(c1.real +c2.real ,c1.imag +c2.imag );
}
Complex operator-(Complex &c1,Complex &c2)
{
return Complex(c1.real-c2.real ,c1.imag -c2.imag );
}
Complex operator*(Complex &c1,Complex &c2)
{
return Complex(c1.real*c2.real-c1.imag *c2.imag ,c1.imag *c2.real +c1.imag *c2.real );
}
Complex operator/(Complex &c1,Complex&c2)
{
return Complex()//除法实现起来比较麻烦。。这里我就不说了。。
}
istream& operator>>(istream& input,Complex &c)
{
cout<<"input real and imag:"<<endl;
input>>c.real >>c.imag ;
return input;
}
ostream& operator<<(ostream& output,Complex &c)
{
output<<c.real;
if(c.imag >0)
cout<<"+";
cout<<c.imag <<"i"<<endl;
return output;
}
int main()
{
Complex c1,c2,c3,c4,c5;
double d=4.7;
//d=d+c1;
cin>>c1>>c2;
cout<<d<<endl;
c3=c1+c2;
c4=c1-c2;
c5=c1*c2;
cout<<c3<<c4<<c5;
c4=c4+Complex(4.7);//这里有个问题?c4=c4+4.7不行?编译器不能自动把double型转换成Complex型?
cout<<c4;
return 0;
}