【问题标题】:linker error when overriding operator<< in visual C++在 Visual C++ 中覆盖 operator<< 时出现链接器错误
【发布时间】:2020-09-20 08:36:19
【问题描述】:

我有一个模板类“LinkedList”,我想做的是覆盖

所以我有一个像这样的头文件:

#pragma once
#include <cstdlib>
#include <iostream>
#include "Node.h"

using namespace std;

template <class T> class LinkedList
{
    public:
        LinkedList<T>() { this->head = nullptr; listSize = 0; };
        ~LinkedList();
        friend ostream& operator<< (ostream& outputStream, LinkedList<T>& list);

        //we don't check if you're putting in a duplicate to keep the insert at O(1)
        //you're on your own if you do that
        void insert(T* item); 

        //O(n) worst case, O(1) best case, we move queried items to the front, to get more best cases
        T* find(T item); //returns nullptr if not found
        T* find(int key);

        T* first();

        //complexity same as find
        bool remove(int key);
        bool remove(T item);

        int length() { return listSize; }


    private:
        Node<T>* head;
        Node<T>* findItemNeighbors(int item, Node<T>* prev, Node<T>* next);
        unsigned int listSize;

};

我有一个类文件,其中包含各种实现,还有这个人:

ostream& operator<<(ostream& outputStream, LinkedList<T>& list)
{
    Node<T>* current = list.head;
    while (current != nullptr)
    {
        outputStream << *(current->item) << " -> ";
        current = current->next;
    }
    return outputStream;
}

现在,问题是,当我尝试编译时。我收到链接器错误,但只有当我尝试在 main 中使用运算符时,如下所示:

LinkedList<Employee>* list = new LinkedList<Employee>();
Employee* test4 = new Employee("Alex", "Herbert", 1101);
list->insert(test4);
cout << *list << "\n";

而链接器错误,在其所有辉煌的清晰度是:

我在这里缺少什么?否则一切都可以正常编译,直到我尝试在该类型上使用

【问题讨论】:

    标签: visual-c++ operator-overloading linker-errors


    【解决方案1】:

    编辑:我在这里写的一切都是错误的。

    诀窍在于如何处理模板友元函数,以及编译器如何解释它们。 https://isocpp.org/wiki/faq/templates#template-friends

    TL;DR 是编译器(好吧,我有一些关于 C++ 编译器作者的建议)假设友元函数是常规类型,而不是模板类型。

    所以,对于朋友功能,这个可爱的小家伙进入你的功能签名“”

    像这样:

    friend ostream& operator<< <> (std::ostream& outputStream, const LinkedList<T>& list);
    

    现在编译器寻找正确类型的函数,它不会抱怨找不到任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多