I need help fixing an error message - “error LNK20

2019-07-13 15:58发布

I am having this error message whenever I tried to compile

Error   6   error LNK2019: unresolved external symbol "void __cdecl MergeSort(class LinkedList<int> &)" (?MergeSort@@YAXAAV?$LinkedList@H@@@Z) referenced in function _main C:\Users\FOla Yinka\Documents\Visual Studio 2012\Projects\C++\C++\linkedlist.obj    C++
Error   7   error LNK1120: 1 unresolved externals   C:\Users\FOla Yinka\Documents\Visual Studio 2012\Projects\C++\Debug\C++.exe 1   1   C++

I have this in my header file

        template<typename T>
        class LinkedList{
              protected:

              public:
                 friend void MergeSort(LinkedList<T> &list);
        };

        template<typename T>
        void MergeSort(LinkedList<T> &list){

        }

To check if the fault is in the function declaration, I turned all the protected members public and I removed the friendship so MergeSort can have access to all memebers and then the program compiled successfully. I don't know why I am having this error message.

2条回答
淡お忘
2楼-- · 2019-07-13 16:33

The problem is that once your class template is instantiated for (say) T=int, the friend declaration declares the existence of a non-template function:

 friend void MergeSort(LinkedList<int> &list);

In your code, this function does not exist. There is a function template called MergeSort(), but that is not the same thing you are declaring as a friend.

查看更多
太酷不给撩
3楼-- · 2019-07-13 16:53

A possible solution is to define the friend within the class body:

template<typename T>
class LinkedList{
      protected:

      public:
        friend void MergeSort(LinkedList<U> &list)
        {}
};

The other solution is to declare the friend before the class body so that it knows the friend is a template:

template <typename T> class LinkedList ;
template <typename T>  void MergeSort(LinkedList<T> &list) ;

and then in the class body declare the friend like this:

friend void MergeSort<>(LinkedList<T> &list) ;

This C++ FAQ entry goes into the complete details of why you need a special work-around in this case.

查看更多
登录 后发表回答