1

伙计们,我正在尝试为我的类 SortedList 创建一个模板。我想重载 << 运算符,所以我在类中声明了一个友元函数,但每次我尝试编译 main.cpp 时都会出现以下错误:template-id 'operator<< ...' does not match any模板声明。这是来自 main.cpp 的代码

int main()
{
    SortedList<int, int> lst, lst2;
    int a = 2;
    lst.addItem(2, 3);
    cout << lst << endl;
    return 0;
}

这是模板类的声明和定义

template <typename K, typename V>
struct Node
{
    K key;
    V value;
    Node<K, V>* next;
};
template <typename K, typename V>
class SortedList
{
friend ostream& operator << <K, V>(ostream&, const SortedList&);
public:

    SortedList();
    SortedList(const SortedList&);
    SortedList& operator = (const SortedList&);
    ~SortedList();

    void addItem(const K&, const V&);
    void removeElem(const K&);
    void removeAt(int);
    bool remove(const K&);


private:

    Node<K, V>* start;
    size_t n;

};
4

1 回答 1

2

好吧,您可以在C++ 常见问题上找到一个很好的解释,也许我会引用它:

当编译器在类定义中正确地看到友元行时,就会发生障碍。那时它还不知道友元函数本身就是模板。

当您调用 operator+ 或 operator<< 函数时,此假设会导致编译器生成对非模板函数的调用,但链接器会给您一个“未定义的外部”错误,因为您从未真正定义过这些非模板函数。

一种解决方案是:

template<typename K, typename V> class SortedList;
template<typename K, typename V> std::ostream& operator<< (std::ostream& o, const SortedList<K,V>& x);

最重要的是,是您的课程示例(编译完美,只是什么都不做)。

于 2014-05-27T09:56:53.133 回答