zoukankan      html  css  js  c++  java
  • Effective C++ 笔记 —— Item 10: Have assignment operators return a reference to *this.

    For this code:

    int x, y, z;
    x = y = z = 15; // chain of assignments

    The way this is implemented is that assignment returns a reference to its left-hand argument, and that’s the convention you should follow when you implement assignment operators for your classes:

    class Widget 
    {
    public:
        //...
        Widget& operator=(const Widget& rhs) // return type is a reference to the current class
        {
            //...
            return *this; // return the left-hand object
        }
        //...
    };
    
    //This convention applies to all assignment operators, not just the standard form shown above.Hence:
    
    class Widget
    {
    public:
        //...
        Widget& operator+=(const Widget& rhs) // the convention applies to +=, -=, *=, etc.
        { 
            // ...
            return *this;
        }
        Widget& operator=(int rhs) // it applies even if the operator’s parameter type is unconventional
        { 
            return *this;
        }
        //...
    };

    Things to Remember

    • Have assignment operators return a reference to *this.
  • 相关阅读:
    url protocol
    wpf webbrowser取消js报错
    c#端口扫描器wpf+socket
    c#协变 抗变
    MTK刷机快捷键
    iTextCharp c#
    wince可用的7-zip
    直播平台搭建与相关资料
    pyinstall
    面向对象常见的术语
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15205111.html
Copyright © 2011-2022 走看看