簡體   English   中英

有關功能/操作員超載的困惑

[英]Confusion regarding Function/operator overloading

考慮下面的自包含程序。

#include <iostream>
template<typename Ty>
struct Foo
{
    Foo& operator=(Foo foo){ return foo; }    
private:
    Foo& operator=(Foo& foo){ return foo; }
};
template<typename Ty>
struct Bar
{
    template<typename U>
    Bar& operator=(Bar<U> bar){ return bar; }
private:
    Bar& operator=(Bar& bar){ return bar; }
};

int main()
{
    Foo<int> f1, f2;
    f1 = f2;            // (1)
    Bar<int> b1, b2;
    b1 = b2;            // (2)
    f1 = Foo<int>(f2);  // (3)
    b1 = Bar<int>(b2);  // (4)
}

FooBar重載了賦值運算符,並且在使用它們兩者時均無法編譯,除非我們將其顯式轉換為對象的類型。 另外,盡管FooBar的分配均失敗,但是失敗有所不同。 注意,我確實理解了當基於引用和值的函數重載時,為什么調用不明確。 但是我不明白的是

  1. 為什么使用顯式模板參數會更改編譯器故障。 語句(1)和(2)給出了不同的錯誤,其中(1)聲明該調用是模棱兩可的,而(2)聲明它無法訪問私有數據成員。 對於前。 使用VC ++進行編譯時(與g ++相似的行為),我看到以下錯誤

     1>Source.cpp(8): warning C4522: 'Foo<int>' : multiple assignment operators specified 1> Source.cpp(20) : see reference to class template instantiation 'Foo<int>' being compiled 1>Source.cpp(21): error C2593: 'operator =' is ambiguous 1> Source.cpp(7): could be 'Foo<int> &Foo<int>::operator =(Foo<int> &)' 1> Source.cpp(5): or 'Foo<int> &Foo<int>::operator =(Foo<int>)' 1> while trying to match the argument list '(Foo<int>, Foo<int>)' 1>Source.cpp(23): error C2248: 'Bar<int>::operator =' : cannot access private member declared in class 'Bar<int>' 1> Source.cpp(15) : see declaration of 'Bar<int>::operator =' 
  2. 為什么我執行顯式強制轉換的(3)和(4)都不會失敗。 為什么它不是模棱兩可的,也不是為什么它試圖訪問私有的引用重載。

  3. 為什么在情況(2)中,相對於值重載的函數/運算符,它優先考慮參考重載。

注意如果要使用代碼, 使用IDEONE版本。 注意您能否提供適當的參考。

  1. Foo::operator=兩個重載對於重載解析目的都是相同的良好匹配-因此不明確。 Bar::operator=並非如此-在其他條件相同的情況下,重載解析更傾向於使用非模板而不是模板。 因此,私有operator=是更好的匹配-但當然,它隨后將無法通過訪問檢查。

  2. Foo<int>(f2)是臨時的,不能綁定到非常量引用。 以值作為參數的過載是唯一可行的選擇。

  3. 它不優先考慮引用重載-它優先考慮非模板重載。 您可以通過切換來確認。

暫無
暫無

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

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