C++ Convert Operator和其他Operator的應用情境比較

來源:互聯網
上載者:User
在看lftp的原始碼的時候,發現這麼一行:

operator bool() const { return ... }

一下子沒想起來,這是什麼文法,是operator overload嗎?不像阿,怎麼不以函數的傳回值打頭呢?後來一查C++ Primer,明白了,這是convert operator,也就是將這個類如果要轉化成bool值的話,就會調用到這個函數。convert operator以operator關鍵字打頭,緊跟類型,然後是兩個括弧(括弧中不能帶有參數)。更具體的看C++ Primer和上面的注釋。

不過看明白了之後有個問題:

operator int() const { ...... }
bool operator<(int input) { ...... }

就是如果這兩個operator都定義了(一個是convert op, 一個是arithmetic op),那麼,在實際代碼中會用到哪個呢?為此,寫了一小段測試代碼:

Code: Select all
#include <iostream>
using namespace std;

class A {
    public:
        operator int() const { cout << "INT Convert function called..." << endl; return content; }
        bool operator<(int input) {
            cout << "Less operator function called..." << endl;
            if (content < input)
                return true;
            else
                return false;
        }
       
        void setContent(int value) { content = value; }
    private:
        int content;
};

int main()
{
    A a;
    a.setContent(10);
    if (a < 100)
        cout << "Class A is less than 100..." << endl;
    else
        cout << "Class A is larger than 100..." << endl;

    cout << "The abs of class A is: " << abs(a) << endl;
    return 0;
}

測試結論是,第一個調用:if (a < 100),調用的是arithmetic op;第二個調用abs(a),使用的是convert op。所以,現在有答案了:

1. 當有精確匹配時,比如a < 100這種,肯定使用精確匹配。因為如果使用convert op將a變成int,然後比較的話,要經過一個convert的過程;< operator這個函數是精確匹配,所以,肯定用這個。

2. 第二個調用無法使用arithmetic op,所以,只能用convert op,將a轉化成int。在實際編碼過程中,除了這種情況,還有一些情況也會用到convert op。比如,class就定義了< operator,沒定義>,那麼,碰到if (a > 100)這種的時候,就只能使用convert op了。

3. 避免出現ambiguous的情況。比如,如果我們代碼這樣寫:if (a < 100.00),那麼,編譯就無法通過了。因為如果使用arithmetic op,那麼,需要將100.00轉化成int,才滿足arithmetic op的參數要求;但是如果使用convert op,也需要將產生的int轉化成double,才能和100.00做比較。這樣一來,編譯器就無法分辨這兩種方案的優先順序了,自然編譯就會出錯了。

OK, That's all.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.