C++ STL 重載運算子小於符號的巧妙

來源:互聯網
上載者:User
一天,無意中看到如下類定義:

            class Foo

            {

                    int a1;

                    int a2;

                   //方案一

                     bool operator<(const Foo& other)  const //類字典序比較方式

                    {

                            return ((a1<other.a1) || (!(other.a1<a1) && (a2<other.a2));

                    }

            }

        怪在哪呢?就怪在粗體字的部分的,看上去挺彆扭的寫法,不就是

            //方案二

            bool operator<(const Foo& other)  const

            {

                if(a1<other.a1 || (a1==other.a1 && a2<other.a2))

                    return true;

                return false;

            }

        這樣不是更清晰?!難道是妙在少了一行代碼???

       其實謎底在於,方案一隻用了一個小於符號,而方案二卻用了小於符號與等號,多了一個等號;更正式來說

是要多重載一個==號,例子中的a1,a2是基本類型,其==操作已預設實現,但當a1或a2為類時,就得自己重

載a1或a2的“==”運算子了。

        換言之,在a1或a2為對象時,

                方案一:只須重載小於運算子

                方案二:必須重載小於運算子以及“==”運算子

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.