第十一周——实现类中的运算符重载

来源:互联网 发布:linux版本查看命令 编辑:程序博客网 时间:2024/06/05 08:23
  1. /* 
  2. *Copyright (c) 2015,烟台大学计算机学院 
  3. *All rights reserved. 
  4. *文件名称:text.cpp 
  5. *作者:李德彪
  6. *完成日期:2015年5月16日 
  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. Complex Complex::operator+(const Complex&c2)  
  30. {  
  31.     return Complex(real+c2.real,imag+c2.imag);  
  32. }  
  33.     Complex Complex::operator-(const Complex&c2)  
  34.     {  
  35.         return Complex(real-c2.real,imag-c2.imag);  
  36.     }  
  37.     Complex Complex::operator*(const Complex&c2)  
  38.     {  
  39.         return Complex(real*c2.real,imag*c2.imag);  
  40.     }  
  41.     Complex Complex::operator/(const Complex&c2)  
  42.     {  
  43.         return Complex(real/c2.real,imag/c2.imag);  
  44.     }  
  45.    void Complex:: display()  
  46.    {  
  47.        cout<<"("<<real<<","<<imag<<")"<<endl;  
  48.    }  
  49. int main()  
  50. {  
  51.     Complex c1(3,4),c2(5,-10),c3;  
  52.     cout<<"c1=";  
  53.     c1.display();  
  54.     cout<<"c2=";  
  55.     c2.display();  
  56.     c3=c1+c2;  
  57.     cout<<"c1+c2=";  
  58.     c3.display();  
  59.     c3=c1-c2;  
  60.     cout<<"c1-c2=";  
  61.     c3.display();  
  62.     c3=c1*c2;  
  63.     cout<<"c1*c2=";  
  64.     c3.display();  
  65.     c3=c1/c2;  
  66.     cout<<"c1/c2=";  
  67.     c3.display();  
  68.     return 0;  
  69. }  
0 0