/*
* 程序的版权和版本声明部分
* Copyright (c)2013, 在校学生
* All rightsreserved.
* 文件名称: 项目Complex.cpp
* 作 者:刘旺
* 完成日期:2014年3月16日
* 版本号: 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);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c2)
{
Complex p ;
p.real = c2.real+real ;
p.imag = c2.imag+imag ;
return p ;
}
Complex Complex::operator-(Complex &c2)
{
Complex p ;
p.real = c2.real+real ;
p.imag = c2.imag+imag ;
return p ;
}
//(a+bi)(c+di)=(ac-bd)+(bc+ad)i
Complex Complex::operator*(Complex &c2)
{
Complex p ;
p.real = c2.real*real-c2.imag*imag ;
p.imag = c2.imag*real+c2.real*imag ;
return p ;
}
// (a+bi)/(c+di)
//=[(a+bi)(c-di)]/[(c+di)(c-di)]
//=[(ac+bd)+(bc-ad)i]/(c^2+d^2)
Complex Complex::operator/(Complex &c2)
{
Complex p ;
p.real = (real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag) ;
p.imag = (imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag) ;
return p ;
}
void Complex::display()
{
cout << '('<< real << ',' << imag << "i)" << endl ;
}
int main()
{
Complex c1(3,4),c2(5,-10),c3;
cout<<"c1=";
c1.display();
cout<<"c2=";
c2.display();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=c1-c2;
cout<<"c1-c2=";
c3.display();
c3=c1*c2;
cout<<"c1*c2=";
c3.display();
c3=c1/c2;
cout<<"c1/c2=";
c3.display();
return 0;
}
运算符的重载是我感觉到在C++中我们可以控制很多东西来实现自己想法。