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

  1. /* 
  2. *Copyright (c) 2016,烟台大学计算机学院 
  3. *All rights reserved. 
  4. *文件名称:main.cpp 
  5. *作    者:李德彪
  6. *完成时间:2016年5月23日 
  7. *版 本 号:v1.0 
  8. * 
  9. *问题描述:项目-实现复数类中的运算符重载。 
  10. *输入描述:无。 
  11. *程序输出:两个数的算法公式及结果。 
  12. */  
  13. #include <iostream>    
  14. using namespace std;    
  15. class Complex     
  16. {    
  17. public:    
  18.     Complex(){real=0;imag=0;}    
  19.     Complex(double r,double i){real=r; imag=i;}    
  20.     Complex operator+(const Complex &c2);    
  21.     Complex operator-(const Complex &c2);    
  22.     Complex operator*(const Complex &c2);    
  23.     Complex operator/(const Complex &c2);    
  24.     void display();    
  25. private:    
  26.     double real;    
  27.     double imag;    
  28. };    
  29. //下面定义成员函数    
  30. Complex Complex::operator+(const Complex &c2)   
  31. {  
  32.     Complex c;  
  33.     c.real=real+c2.real;  
  34.     c.imag=imag+c2.imag;  
  35.     return c;  
  36. }  
  37. Complex Complex::operator*(const Complex &c2)  
  38. {  
  39.       
  40.     Complex c;  
  41.     c.real=real*c2.real-imag*c2.imag;    
  42.     c.imag=imag*c2.real+real*c2.imag;  
  43.     return c;  
  44.   
  45. }    
  46. Complex Complex::operator/(const Complex &c2)  
  47. {  
  48.       
  49.     Complex c;  
  50.     c.real=(real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);    
  51.     c.imag=(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);    
  52.     return c;  
  53.   
  54. }   
  55. Complex Complex::operator-(const Complex &c2)  
  56. {  
  57.       
  58.     Complex c;  
  59.     c.real=real-c2.real;  
  60.     c.imag=imag-c2.imag;  
  61.     return c;  
  62.   
  63. }   
  64. void Complex::display()  
  65. {  
  66.     cout<<"("<<real<<","<<imag<<"i)"<<endl;   
  67. }  
  68. //下面定义用于测试的main()函数    
  69. int main()    
  70. {    
  71.     Complex c1(3,4),c2(5,-10),c3;    
  72.     cout<<"c1=";    
  73.     c1.display();    
  74.     cout<<"c2=";    
  75.     c2.display();    
  76.     c3=c1+c2;    
  77.     cout<<"c1+c2=";    
  78.     c3.display();    
  79.     c3=c1-c2;    
  80.     cout<<"c1-c2=";    
  81.     c3.display();    
  82.     c3=c1*c2;    
  83.     cout<<"c1*c2=";    
  84.     c3.display();    
  85.     c3=c1/c2;    
  86.     cout<<"c1/c2=";    
  87.     c3.display();    
  88.     return 0;    
  89. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值