C++中重载运算符

重载运算符的函数一般格式如下:

重载运算符 operator 运算符名称(形参表列)

例如,想将“+”用来Complex类(复数类)的加法计算,函数的原型可以:

Complex operator+(Complex &c1,Complex &c2);

 

operator是关键字,专门用来定义重载运算符的函数的。我们可以把operator+看作函数名,意思是“对运算符+重载”

 

 

Cpp代码  收藏代码
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. //复数  
  7. class Complex  
  8. {  
  9. private:  
  10.     double real;  
  11.     double imag;  
  12. public:  
  13.     Complex()  
  14.     {  
  15.         real=0;  
  16.         imag=0;  
  17.     }  
  18.     Complex(double r,double i)  
  19.     {  
  20.         real=r;   
  21.         imag=i;  
  22.     }  
  23.     Complex operator+(Complex &c2);  
  24.     void display();  
  25. };  
  26.   
  27. //把operator+看作函数  
  28. Complex Complex::operator+(Complex &c2)  
  29. {  
  30.     Complex c;  
  31.     c.real=real+c2.real;  
  32.     c.imag=imag+c2.imag;  
  33.     return c;  
  34. }  
  35.   
  36. void Complex::display()  
  37. {  
  38.     cout<<"("<<real<<","<<imag<<"i)"<<endl;  
  39. }  
  40.   
  41. int main(int argc, char* argv[])  
  42. {  
  43.     Complex c1(3,4),c2(5,-10),c3;  
  44.     c3=c1+c2;  
  45.     cout<<"c1=";c1.display();  
  46.     cout<<"c2=";c2.display();  
  47.     cout<<"c3=";c3.display();  
  48.     return 0;  
  49. }  
 
posted @ 2011-08-08 14:42  麦飞  阅读(241)  评论(0编辑  收藏  举报