zoukankan      html  css  js  c++  java
  • 操作符重载

      今天在看《Effective C++》的Item 10时,书中说道,赋值操作符需要返回的是对*this的引用。
    例如:

    class Widget {
    public:
        ...
        Widget& operator += (const Widget& rhs)
        {
            ...
            return *this;
        }
        
        Widget& operator = (const Widget& rhs)
        {
            ...
            return *this;
        }
    };

      

      因此,我也尝试着重载了一下其他操作符,发现上面的条款只是对操作符 -=   +=   =   *=   /= 这些包含赋值操作符。而对于+ - * / 这些操作符则不能按照以上条款!

      

    class myint
    {
    public:
        myint(int i = 0): _i(i)
        {
    
        }
    
        ~myint()
        {
    
        }
    
        myint& operator=(const myint& rhs)
        {
            _i = rhs._i;
            return *this;
        }
    
        //return myint, it is a temp var
        myint operator+(const myint& rhs)
        {
            myint temp;
            temp._i = _i + rhs._i;
            return temp;
        }
    
        myint& operator+=(const myint& rhs)
        {
            _i += rhs._i;
            return *this;
        }
    
        myint operator-(const myint& rhs)
        {
            myint temp;
            temp._i = _i - rhs._i;
            return temp;
        }
    
        myint& operator-=(const myint& rhs)
        {
            _i = _i - rhs._i;
            return *this;
        }
    
        myint operator*(const myint& rhs)
        {
            myint temp;
            temp._i = _i * rhs._i;
            return temp;
        }
    
        void result()
        {
            cout<<_i<<endl;
        }
    private:
        int _i;
    };
  • 相关阅读:
    MOXA串口服务器使用
    【笔记】Winform设置快捷键
    comboBox联动
    【笔记】winform窗体显示
    关于xml文件的使用
    day_6
    day_5
    dau_4
    day_3
    day_2
  • 原文地址:https://www.cnblogs.com/wiessharling/p/4167370.html
Copyright © 2011-2022 走看看