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

    c++ 的运算符的操作对象是简单的类型,比如 +  既可以用于整形加,也可以用于浮点型加。但是很多时候对于用户自定义的类型也需要相关的操作。这时就需要重载运算符

    定义运算符的重载可以使程序简单明了。

    1:按照是否 可以重载 和 重载函数的类型,可以分为下面四类:

        1>sizeof, . , .* ,:: , ? : 不能重载

        2>  = , -> ,[],() 只能重载为普通函数成员

        3>  new delete  不能重载为普通函数成员

        4>  其他的不能重载为静态函数成员,但可以重载为普通函数成员和 普通函数 

    2:重载为普通函数

         函数定义的基本格式:

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

        参数个数=运算符目数

        调用的时候:

        比如    operator 运算符 (参数表1  , 参数表2)  {   函数体  }

        参数1 运算符 参数2.  比如 加入重载了 +, 则a+b 等价于  operator+(a,b);

       

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class num
    {
        public:
        int n;
        num(int n):n(n){}
    };
    num operator+(int  a, num b) //从左向右分别是参数1  参数2
    {
         num temp=a-b.n;
         return temp;
    }
    int main()
    {
         num x=5;
         int y=9;
         //num z=x+y; 左边是参数1 ,右边是参数2
          num z=y+x;
         cout<<z.n<<endl;
         system("pause");
         return 0;
    }
    

      3:重载为普通函数成员:

              参数个数=运算符目数-1;

              一般格式:

              类 A{

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

              对于双目运算符而言,参数表只要一个参数,它是运算符的右操作数,当前对象(即this指针所指的对象)为左操作数。

              

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class num
    {
        public:
        int n;
        num(int n):n(n){}
        num operator+(int a);
    };
    num num::operator+(int  a) //从左向右分别是参数1  参数2
    {
         num temp=a-n;
         return temp;
    }
    int main()
    {
         num x=5;
         int y=9;
         num z=x+y;   //当前对象是参数1 即x ,y是参数2
          //num z=y+x;
         cout<<z.n<<endl;
         system("pause");
         return 0;
    }
    

      对于单目运算符而言,参数表没有参数,但是隐含一个参数,即this指针所指的当前对象:

          

    #include<iostream>
    #include<stdio.h>
    #include<string>
    using namespace std;
    class num
    {
        public:
        int n;
        num(int n):n(n){}
        num &operator++();
    };
    num & num::operator++() //从左向右分别是参数1  参数2
    {
        n++;
        return *this;
    
    }
    int main()
    {
         num x=5;
         ++x;
         cout<<x.n<<endl;
         system("pause");
         return 0;
    }
    

       

  • 相关阅读:
    mysql
    mysql
    mysql
    mysql
    mysql
    mysql
    mysql
    mysql
    mysql
    为你的react项目添加路由
  • 原文地址:https://www.cnblogs.com/cs1003/p/2833137.html
Copyright © 2011-2022 走看看