zoukankan      html  css  js  c++  java
  • 二元运算符重载

    运算符重载是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);

    }

  • 相关阅读:
    DS博客作业03--栈和队列
    DS博客作业02--线性表
    DS博客作业01--日期抽象数据类型设计与实现
    C语言博客作业06--结构体&文件
    DS博客作业08--课程总结
    DS博客作业07--查找
    DS博客作业06--图
    DS博客作业05--树
    DS博客大作业--树 (陈梓灿组)
    DS博客作业03--栈和队列
  • 原文地址:https://www.cnblogs.com/lyjbk/p/12819155.html
Copyright © 2011-2022 走看看