簡體   English   中英

重載重載運算符

[英]Overloading overloaded operators

#include <iostream>
#include <fstream>
using namespace std;

class binaryOperators 
{
    public:
        int i;

        binaryOperators (int tempI = 0)
        {
            i = tempI;
        }

        binaryOperators operator<< (const binaryOperators &right);
};

binaryOperators operator<< (const binaryOperators &left, const binaryOperators &right)
{
    cout << "\nOne";
    return left;
}

binaryOperators binaryOperators :: operator<< (const binaryOperators &right)
{
    cout << "\nTwo";
    return *this;
}

int main ()
{   
    binaryOperators obj;

    // Compiler's behavior: This statement calls the overloaded operator << declared inside the class.
    obj << 5 << 3 << 2;
    // Compiler's behavior: This statement calls the overloaded operator << declared outside the class.
    2 << obj;

    return 0;
}

我在main()函數中寫了注釋。
這種編譯器行為的原因是什么?

此行為編譯器是否依賴?

Linux上的GCC

您所看到的行為是由const正確性引起的。 在類中定義的operator <<是非const的,因此它只能在非const對象或引用上操作,例如obj。 類外的非成員版本有兩個常量操作數。

如果您將成員版本編寫為非成員,它將如下所示:

binaryOperators operator<< (binaryOperators &left, const binaryOperators &right)
{
    cout << "\nTwo";
    return left;
}

當重載匹配時,編譯器選擇最佳匹配。 在第一種情況下,左操作數是非常量的,因此它選擇成員操作符。 在第二種情況下,左操作數是一個rvalue(臨時binaryOperators),它被引用為const,因此選擇了非成員運算符。

這種行為完全有道理:

  • 當成員函數存在並匹配時,最好使用它而不是自由函數,否則類外部的代碼可能會無意中破壞類封裝(例如,如果另一個成員函數使用operator<< )。

  • 自動轉換通過創建候選函數列表,然后嘗試查找需要它的任何參數的轉換來工作。 為了找到成員函數,必須在構建候選列表之前進行轉換,因此只能找到自由函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM