/*
* 程序的版权和版本声明部分
* Copyright (c)2013, 烟台大学计算机学院学生
* All rightsreserved.
* 文件名称: object.cpp
* 作 者: 徐凯旋
* 完成日期: 2013年05月05日
* 版 本 号: v1.0
*/
#include <iostream>
#include <Cstring>
using namespace std;
class Complex
{
public:
Complex( ){real=0;imag=0;}
//实现输入输出运算符重载
friend istream& operator>>(istream &cin,Complex&c);
friend ostream& operator<<(ostream &cout,Complex&c);
//实现加减乘除运算符重载
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);
friend istream& operator>>(istream &cin,Complex&c);
friend ostream& operator<<(ostream &cout,Complex&c);
private:
double real;
double imag;
};
//成员函数的定义
Complex operator+(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real+c2.real;
c.imag=c1.imag+c2.imag;
return c;
}
Complex operator-(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real-c2.real;
c.imag=c1.imag-c2.imag;
return c;
}
Complex operator*(Complex &c1,Complex &c2)
{
Complex c;
c.real=c1.real*c2.real-c1.imag*c2.imag;
c.imag=c1.imag*c2.real+c1.real*c2.imag;
return c;
}
Complex operator/(Complex &c1,Complex &c2)
{
Complex c;
c.real=(c1.real/c2.real+c1.imag/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(c1.imag/c2.real-c1.real/c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
//输入输出运算符重载
istream & operator>>(istream&cin,Complex&c)
{
cout<<"请输入复数的实部与虚部"<<endl;
cin>>c.real>>c.imag;
return cin;
}
ostream & operator<<(ostream &cout,Complex&c)
{
cout<<"(";
cout<<c.real;
cout<<","<<c.imag<<"i)"<<endl;
return cout;
}
//main函数经行测试
int main( )
{
Complex c1,c2,c3;
cin>>c1>>c2;
cout<<c1<<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;
system("PAUSE");
return 0;
}
运行结果: