【问题标题】:Unexpected error when creating a friend template function创建好友模板函数时出现意外错误
【发布时间】:2014-05-27 09:34:16
【问题描述】:

伙计们,我正在尝试为我的类 SortedList 创建一个模板。我想重载

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;

};

【问题讨论】:

  • friend ostream&amp; operator &lt;&lt; &lt;K, V&gt;(ostream&amp;, const SortedList&amp;);:如果你使用这样的语法,你应该在SortedList类模板定义之前和它的前向声明之后声明operator &lt;&lt;模板。

标签: c++ class templates operator-overloading friend-function


【解决方案1】:

你可以在C++ faq 上找到一个很好的解释,也许我会引用它:

当编译器看到友行在 类定义正确。那一刻它还不知道 朋友函数本身就是模板。

当你打电话给运营商时+ 或 operator

一种解决方案是:

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

最重要的是,Here 是你的类的示例(编译完美,只是什么都不做)。

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多