zoukankan      html  css  js  c++  java
  • 运算符重载(我转的)



    转分享不如转载好,但是这里不能转载,只好复制了!


    重写操作符的时候 const A& operator (符号)(参数){} 
    如果第一个参数为常量的时候,例如CLASSA m = 1 + m; 
    那么要定义友元类friend const A& operator(int i, A& m){};

    一般操作符的左边的那个为调用者本人,操作符右侧的类是参数作为加入

    单元运算的时候,左++ 和 右++为了区分需要用一个int型的参数加以区分。

    const A& operator ++ () { // 左,且要临时多加一个A类多想作为返回值,因为左++,当前的返回值不改变。

    }

    const A& operator ++(int){ //右侧

    }

    // test.cpp : 定义控制台应用程序的入口点。
    //

    #include "stdafx.h"

    class A{
    public:
     explicit A(int num){
      b = num;
     }
     A(){
      b = 0;
     }
     const A& operator++(){
      b++;
      return *this;
     }
     const A& operator++(int){
      A t(b);
      ++b;
      return t;
     }
     void write(const A a){
      printf("current value: %d\n", a.b);
     }
     const A &operator =(const A &j){
      if(&j == this) return *this; 
      b = j.b;
      return *this;
     }
     const A &operator =(int j){  
      b = j;
      return *this;
     }
     const A &operator +(const A &j){A t; t.b=b+j.b; return t;}
     const A &operator +=(const A &j){this->b=b+j.b; return *this;};
     friend const A &operator +(int i ,const A &j){A t; t.b=i+j.b; return t;}
    private:
     int b;
    };

    int _tmain(int argc, _TCHAR* argv[])
    {
     A a(100), b(200);
     //a = operator + (3, b); a.write(a);
     a += b;
     a = 1;
     a.write(a);


     a.write(++a);

     a.write(a++);

     a.write(a);
     system("pause");
     return 0;
    }

    我转的人家的:
    http://www.cnblogs.com/25-to-life/archive/2011/10/13/2211033.htm

  • 相关阅读:
    Js--小笔记
    Android Gson解析
    java格式化数字、货币、金钱
    关于Edittext默认弹出软键盘为数字键
    生日星座自动匹配
    ANDROID STUDIO系列教程六--GRADLE多渠道打包
    框架,简化了代码的同时,也让我们慢慢变蠢
    Android开发实现高德地图定位
    onNewIntent调用时机
    EditText输入手机号自动带空格
  • 原文地址:https://www.cnblogs.com/leisure/p/2213085.html
Copyright © 2011-2022 走看看