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;
    };
  • 相关阅读:
    DOM、Window对象操作
    JavaScript基础
    关于样式表的两个练习
    css样式表
    表单
    HTML的格式、内容容器、表格标签
    C#部分的总结
    Android自定义View之音频条形图
    String, StringBuilder, StringBuffer问题
    详解Java中ArrayList、Vector、LinkedList三者的异同点(转)
  • 原文地址:https://www.cnblogs.com/wiessharling/p/4167370.html
Copyright © 2011-2022 走看看