第十二周项目1实现复数类中的运算符重载1


  1. /* 
  2.  
  3. *Copyright (c) 2016,烟台大学计算机学院 
  4.  
  5. *All rights reserved. 
  6.  
  7. *文件名称 : 
  8.  
  9. *作 者 : 刘默涵 
  10.  
  11. *完成日期 : 2016年5月25号 
  12.  
  13. *版 本 号 : v6.0 
  14.  
  15. * 
  16.  
  17. *问题描述 : 
  18.  
  19. */  
  20.   
  21.   
  22. #include<iostream>  
  23. using namespace std;  
  24. class Complex  
  25. {  
  26. public:  
  27.     Complex(){real=0;imag=0;}  
  28.     Complex(double r,double i){real=r;imag=i;}  
  29.     Complex operator+(const Complex &c2);  
  30.     Complex operator-(const Complex &c2);  
  31.     Complex operator*(const Complex &c2);  
  32.     Complex operator/(const Complex &c2);  
  33.     void display();  
  34. private:  
  35.     double real;  
  36.     double imag;  
  37. } ;  
  38. //下面定义成员函数  
  39. Complex Complex::operator+(const Complex &c2)  
  40. {  
  41.     return Complex(this->real+c2.real,this->imag+c2.imag);  
  42. }  
  43. Complex Complex::operator-(const Complex &c2)  
  44. {  
  45.     return Complex(this->real-c2.real,this->imag-c2.imag);  
  46. }  
  47. Complex Complex::operator*(const Complex &c2)  
  48. {  
  49.     return Complex(this->real*c2.real-this->imag*c2.imag,this->real*c2.imag+this->imag*c2.real);  
  50. }  
  51. Complex Complex::operator/(const Complex &c2)  
  52. {  
  53.     return Complex((this->real*c2.real+this->imag*c2.imag)/(c2.imag*c2.imag+c2.real*c2.real),(-this->real*c2.imag+this->imag*c2.real)/(c2.imag*c2.imag+c2.real*c2.real));  
  54. }  
  55. void Complex::display()  
  56. {  
  57.     cout<<"("<<real<<","<<imag<<"i)"<<endl;  
  58. }  
  59. //下面定义用于测试的main()函数  
  60. int main()  
  61. {  
  62.     Complex c1(3,4),c2(5,-10),c3;  
  63.     cout<<"c1=";  
  64.     c1.display();  
  65.     cout<<"c2=";  
  66.     c2.display();  
  67.   
  68.     c3=c1+c2;  
  69.     cout<<"c1+c2=";  
  70.     c3.display();  
  71.   
  72.      c3=c1-c2;  
  73.     cout<<"c1-c2=";  
  74.     c3.display();  
  75.   
  76.      c3=c1*c2;  
  77.     cout<<"c1*c2=";  
  78.     c3.display();  
  79.   
  80.      c3=c1/c2;  
  81.     cout<<"c1/c2=";  
  82.     c3.display();  
  83.     return 0;  
  84. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值