运算符重载01--+号

 Complex.h

 

  
  
  
  
  1. /* 
  2.  + 号运算符重载  
  3. 1.成员函数方式(单目运算符) 
  4. 格式:  返回值类型  operator 符号(参数){} 
  5.  
  6. 2.友元函数格式 (双目运算符) 
  7.  
  8. 格式:  friend 返回值类型  operator 符号(参数){} 
  9.  
  10.  
  11.  
  12. 注意:当两者同时存在时,在Vs2010中优先调用 成员函数重载方式 
  13.  
  14.  
  15.     1. = () []  ->  只能重载为成员函数方式重载 
  16.      
  17.     2.类型转换运算符只能以成员函数方式重载 
  18.  
  19.     3.流运算符只能以友元函数方式重载 
  20.  
  21. */ 
  22. #ifndef _COMPLEX_H_ 
  23. #define _COMPLEX_H_ 
  24. class Complex{ 
  25.  
  26. private: 
  27.  
  28.     int real_; 
  29.  
  30.     int imag_; 
  31. public : 
  32.     Complex(); 
  33.     ~Complex(); 
  34.     Complex(int x , int y); 
  35.     Complex& add(const Complex& c1); 
  36.     //运算符重载声明 
  37.     //成员函数重载方式 
  38.     Complex& operator+(const Complex& c1); 
  39.     //友元函数重载方式 
  40.     friend Complex& operator+(const Complex& c1,const Complex& c2); 
  41.     void display(); 
  42.  
  43. }; 
  44. #endif//_COMPLEX_H_ 

Complex.cpp

 

  
  
  
  
  1. #include<iostream> 
  2. #include"Complex.h" 
  3.  
  4. using namespace std; 
  5.  
  6. Complex::Complex(){ 
  7.  
  8.  
  9.  
  10.     cout<<"Complex constructor"<<endl
  11.  
  12. Complex::~Complex(){ 
  13.  
  14.     cout<<"Complex deconstructor"<<endl
  15.  
  16.  
  17.  
  18. Complex::Complex(int real,int img){ 
  19.  
  20.     this->realreal_ = real; 
  21.  
  22.     this->imag_ = img
  23.  
  24.  
  25. Complex& Complex::add(const Complex& c1){ 
  26.  
  27.     real_+=c1.real_; 
  28.     imag_+=c1.imag_; 
  29.  
  30.     return *this; 
  31.  
  32.  
  33. Complex& Complex::operator+(const Complex& c1){ 
  34.  
  35.     cout<<"member funtion operator +"<<endl
  36.     real_+=c1.real_; 
  37.     imag_+=c1.imag_; 
  38.  
  39.     return *this; 
  40.  
  41.  
  42.  
  43. /**
  44. 实现以友元函数方式重载的+号运算符
  45. */
  46.  Complex& operator+(const Complex& c1, const Complex& c2){ 
  47.  
  48.      cout<<"friend funtion operator +"<<endl
  49.      int img =c1.imag_+c2.imag_; 
  50.  
  51.     int real =  c1.real_ +c2.real_; 
  52.     return Complex(real,img); 
  53.  
  54.  
  55.  
  56. void Complex::display(){ 
  57.  
  58.     cout<<"*********"<<endl
  59.     cout<<this->real_<<"  "<<this->imag_<<endl

调用方式:

 

  
  
  
  
  1. //c1.add(c2); 
  2. //成员函数重载调用方式 
  3. //方式1 
  4. c1+c2; 
  5. //方式2: 
  6. //c1.operator+(c2); 
  7. c1.display(); 
  8. //友元函数重载方式调用 
  9. Complex c3 =c1+c2; 

 

你可能感兴趣的:(运算符,运算符重载)