/*
* 程序的版权和版本声明部分
* Copyright (c)2012, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: object.cpp
* 作者:隋 鑫
* 完成日期: 2013年 5 月 7 日
* 版本号: v1.0
* 输入描述:无
* 问题描述:
* 程序输出:
*/
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(double r,double i){real=r;imag=i;}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
friend ostream&operator<<(ostream&,Complex&);
friend istream&operator>>(istream&,Complex&);
private:
double real;
double imag;
};
ostream&operator<<(ostream&output,Complex&c)
{
output<<"("<<c.real;
if(c.imag>=0) output<<"+";
output<<c.imag<<"i)"<<endl;
return output;
}
istream&operator>>(istream&input,Complex&c)
{
cout<<"input real part and imaginary part of complex number : ";
input>>c.real>>c.imag;
return input;
}
//复数相加: (a+bi)+(c+di)=(a+c)+(b+d)i.
Complex Complex::operator+(Complex &c2)
{
Complex c;
c.real=real+c2.real;
c.imag=imag+c2.imag;
return c;
}
//复数相减:(a+bi)-(c+di)=(a-c)+(b-d)i.
Complex Complex::operator-(Complex &c2)
{
Complex c;
c.real=real-c2.real;
c.imag=imag-c2.imag;
return c;
}
//复数相乘:(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
Complex Complex::operator*(Complex &c2)
{
Complex c;
c.real=real*c2.real-imag*c2.imag;
c.imag=imag*c2.real+real*c2.imag;
return c;
}
//复数相除:(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +(bc-ad)/(c^2+d^2)i
Complex Complex::operator/(Complex &c2)
{
Complex c;
c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
int main()
{
Complex c1,c2,c3;
cin>>c1>>c2;
cout<<"c1="<<c1<<endl;
cout<<"c2="<<c2<<endl;
c3=c1+c2;
cout<<"c1+c2="<<c3<<endl;
c3=c1-c2;
cout<<"c1-c2="<<c3<<endl;
c3=c1*c2;
cout<<"c1*c2="<<c3<<endl;
c3=c1/c2;
cout<<"c1/c2="<<c3<<endl;
return 0;
}
运行结果: