二元运算符重载

运算符重载是C++编译器提供给程序员自定义数据类型参与运算的机制。

二元运算符重载:即参与运算的元素为两个,如+,-;

运算符重载的方法有两种:

(1)将重载函数写为类的内部函数;

(2)将重载函数写为全局函数,友元机制的体现;

程序员要注重从最终的调用表达式逆推重载函数的实现方法:

(1)以+运算符为例:在看到C c3=c1+c2时,要知道+是一个函数,即operator+

  (2)  从运算符的应用模式可以看出,函数具有两个形参,即 operator+(C& c1,C&c2);

  (3)   从接受值类型判断函数的返回值是Void,引用,指针等等。

下面笔者分别用两种方法实现+和- 的重载:

#include <iostream>

using namespace std;

class  temp

{

   public:

      temp(int a,intb)

     { 

       this->my_a=a;

      this->my_b=b;

    }

   ~temp()

  {

   }

//内部函数

  temp   operator-(temp& t)

{

      temp t2=temp(this->-t.a,this->b-t.b);

      return t2;

}

   friend temp operator+(temp &t1,temp &t2);//将全局函数设为类的友元函数

private:

  int my_a; 

  int my_b;

};

//用全局函数实现+运算符重载

temp operator+(temp &t1,temp &t2)

{

      temp  t3(0,0);

     t3=temp(t1.a+t2.a,t2,b+t2.b)

     return  t3;

}

int main()

{

   temp t1(1,2);

   temp  t2(3,4);

    temp t4(0,0);

   temp t5(0,0);

   t4=t1+t2;//等同于 t4=operator(t1,t2);

    t5=t2-t1;//等同于t5=t2.opertaor(t1);

}

猜你喜欢

转载自www.cnblogs.com/lyjbk/p/12819155.html