初探C++运算符重载学习笔记<1>

来源:互联网 发布:淘宝健身教练 编辑:程序博客网 时间:2024/05/16 06:35

运算符重载

 

含义:

 

对抽象数据类型也能够直接使用C++提供的运算符

对已有的运算符赋予多重的含义

使同一运算符针对不同的数据类型产生不同的行为

 

 

目的:

 

-->扩展C++运算符的适用范围,以用于类所表示的抽象数据类型

-->程序更简洁

-->代码可读性更好

 

例如complex_a和complex_b是两个复数对象,如果求和,希望能直接写成

complex_a + complex_b  这样的形式。

 

 

实质:

 

函数重载

返回值类型  operator  运算符(参数表){                 ....}


 

在函数编译时把含运算符的表达式变成对运算符函数的调用。

把运算符的操作数当成运算符函数的参数。

当运算符被多次重载时,根据参数的不同,调用对应的那个重载函数。

 

 

 

举例

 

运算符本身也可以重载为一个普通函数也可以被重载为类的成员函数。

 

重载为普通函数

 

class Complex {   public:     Complex( double r = 0.0, double i= 0.0 )    {     real = r;      imaginary = i;    }  double real;  // real part  double imaginary;  // imaginary part}; 


 

Complex operator+ (const Complex & a, const Complex & b){   return Complex( a.real+b.real, a.imaginary+b.imaginary);}

 

Complex a(1,2), b(2,3), c;c = a + b;



当重载为普通函数时,参数个数为为运算符的数目。

a+b 相当于operator+(a,b)

 

 

 

重载为成员函数

class Complex {  public:    Complex( double r= 0.0, double m = 0.0 ):      real(r),  imaginary(m)  {  }  // constructor    Complex operator+ ( const Complex & );  // addition    Complex operator- ( const Complex & );  // subtraction  private:    double real;  // real part    double imaginary;  // imaginary part};


 

Complex Complex::operator+(const Complex & operand2)  {    return Complex( real + operand2.real,imaginary + operand2.imaginary ); }Complex Complex::operator-  (const Complex &  operand2){   return Complex( real - operand2.real,imaginary - operand2.imaginary  ); }int main(){   Complex x, y(4.3, 8.2), z(3.3, 1.1);   x = y + z;   x = y - z;   return 0;}

 

当重载为成员函数时,参数的个数为运算符的个数减一

此时的y+z 相当于y.operator+(z),因此只需要一个参数。


 



 


 

 


 

 

 

15 0