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

运算符重载

 

含义:

 

对抽象数据类型也能够直接使用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),因此只需要一个参数。


 



 


 

 


 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值