簡體   English   中英

重載operator <<(模板化)時如何修復“模糊過載”錯誤?

[英]How do I fix “ambiguous overload” error when overloading operator<< (templated)?

我試圖重載<<運算符,但我得到以下錯誤:

錯誤:'std :: cout <<“Test”'中'operator <<'的模糊重載

..跟隨50億其他類似的錯誤:

c:\\ mingw \\ bin ../ lib / gcc / mingw32 / 4.5.2 / include / c ++ / ostream:165:7:注意:候選人是:...

這是因為我在main.cpp文件中使用cout。

這是我的代碼:

在BinTree.h中:

    template <typename T>
    class BinTree{
    ...
    friend std::ostream& operator<< <>(std::ostream&, const T&);

在BinTree.cpp中:

    template <typename T>
    std::ostream& operator<< (std:: ostream& o, const T& value){
        return o << value;
    }

在此先感謝您提供任何幫助。

您的函數具有與已定義的簽名相同的簽名。 這就是為什么編譯器會抱怨模糊的過載。 您的函數嘗試定義一個函數以將所有內容流式傳輸到ostream。 此功能已存在於標准庫中。

template <typename T>
std::ostream& operator<< (std:: ostream& o, const T& value){
    return o << value;
}

您可能想要做的是編寫一個函數來定義BinTree如何流式傳輸(到所有內容)。 請注意,流類型是模板化的。 因此,如果將調用鏈接到流運算符,則會傳輸具體類型。

template <typename T, typename U>
T& operator<< (T& o, const BinTree<U>& value){
    //Stream all the nodes in your tree....
    return o;
}

你的意思是..

template<class T>
ostream& operator<<(ostream& os, const BinTree<T>& v){
    typename BinTree<T>::iterator it;
    for(it = v.begin(); it != v.end(); ++it){
                 os << *it << endl;
    }
    return os;
}

發布更多代碼,直到看到這部分:

template <typename T>
std::ostream& operator<< (std:: ostream& o, const T& value){
    return o << value;
}

這只是在呼喚自己。 這是遞歸調用。 operator<<被定義為輸出類型T值,當你寫o<<value ,它調用自身,因為value的類型是T

其次,因為這是函數模板,所以定義應該在.h文件中提供,而不是在.cpp文件中,如果你希望你的代碼通過包含.h文件來工作。

暫無
暫無

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

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