当重载operator<<<<<<<<<<<< (模板)?

时间:2011-10-16 05:36:15

标签: c++ templates compiler-errors overloading operator-keyword

我正在尝试重载<<运算符,但我收到以下错误:

  

错误:'operator<<'的模糊重载在'std :: cout<< “测试”'

..其次是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;
    }

提前感谢您提供任何帮助。

3 个答案:

答案 0 :(得分:6)

您的功能与已定义的功能具有相同的签名。这就是为什么编译器会抱怨模糊的过载。您的函数尝试定义一个函数以将所有内容流式传输到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;
}

答案 1 :(得分:2)

你的意思是......

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;
}

答案 2 :(得分:0)

发布更多代码,直到看到这部分:

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

除了自称之外什么都不做。这是递归调用。 operator<<定义为输出T类型的值,当您编写o<<value时,它会调用自身,因为value的类型为T。< / p>

其次,由于这是函数模板,因此如果您希望代码通过包含.h文件来运行,那么定义应该在.cpp文件中提供,而不是在.h文件中。< / p>