本文介绍了如何解决“歧义过载"问题?重载运算符<< (有模板)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图使<<运算符,但出现以下错误:

I am trying to overload the << operator, but I get the following error:

..紧随其后的是50亿个类似于以下内容的错误:

..Followed by 5 billion other errors similar to:

出现此错误是因为我在main.cpp文件中使用了cout.

This comes up because I'm using cout in my main.cpp file.

这是我的代码:

在BinTree.h中:

In BinTree.h:

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

在BinTree.cpp中:

In BinTree.cpp:

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

预先感谢您可以提供的任何帮助.

Thanks in advance for any help you can give.

推荐答案

您的函数与已定义的函数具有相同的签名.这就是为什么编译器会抱怨模棱两可的重载.您的函数尝试定义一个函数,以将所有内容流式传输到ostream.该功能已经存在于标准库中.

Your function has the same signature than the one already defined. This is why the compiler moans about ambigous overload. Your function tries to define a function to stream everything to a ostream. This function already exists in the standards library.

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

您可能想做的是编写一个函数,该函数定义如何将BinTree流式传输到所有内容.请注意,流类型是模板化的.因此,如果将调用链接到流运算符,它将流传输具体类型.

What you perhaps want to do is write a function that defines how a BinTree is streamed (to everything). Please note that the stream type is templated. So if you chain the calls to the stream operator it streams the concrete type.

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

这篇关于如何解决“歧义过载"问题?重载运算符&lt;&lt; (有模板)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:25