【问题标题】:Linker Error While Trying to Create Linked List Stack [duplicate]尝试创建链接列表堆栈时出现链接器错误[重复]
【发布时间】:2012-09-25 22:19:48
【问题描述】:

可能重复:
Why can templates only be implemented in the header file?
Undefined symbol on a template operator overloading function

对于我的学校作业,我需要制作一个使用链表制作堆栈的程序。我不断收到链接器错误(特别是:error LNK2019: unresolved external symbol "public: __thiscall Stack::Stack(void)" (??0?$Stack@H@@QAE@XZ) referenced in function _main 1>C: \Users\devon.taylor\Desktop\New folder\Debug\PA3.exe : 致命错误 LNK1120: 1 unresolved externals)

这是我的代码:

标题:

template <class T>
class  Stack
{
public:
    Stack();
    Stack(T data);
    ~Stack();
    void push(T data);
    T pop();
    void display();
    bool isEmpty();
    bool isExist(T searchKey);

private:
    Stack<T> *top;
    Stack<T> *next;
    T mData;
};

功能:

#include "stack.h"
#include <iostream>

using namespace std;

template <class T>
Stack<T>::Stack()
{
    top=NULL;
}

template <class T>
Stack<T>::Stack(T data)
{
    mData = data;
    pNext = NULL;
}

template <class T>
Stack<T>::~Stack()
{

}

template <class T>
void Stack<T>::push(T data)
{
   Stack *ptr;
   ptr=new Stack<T>;
   ptr->mData=data;
   ptr->next=NULL;

   if(top!=NULL)
   {
      ptr->next=top;
   }
   top=ptr;
   cout<<"\nNew item inserted to the stack";
}        

template <class T>
T Stack<T>::pop()
{


}
template <class T>
void Stack<T>::display()
{

}

主要功能:

#include <iostream>
#include "stack.h"

using namespace std;

void main ()
{
    Stack<int>* stack;
    stack = new Stack<int>;
    //stack->push(19);



    system("pause");
}

【问题讨论】:

  • 不相关,但是在push的时候不需要测试top是不是NULL

标签: c++ templates linked-list stack


【解决方案1】:

您必须在头文件中实现模板函数,以便链接器获取它。有关详细信息,请参阅此question

另外,请查看C++ FAQ 了解更多详情。

【讨论】:

  • 你能解释一下你的意思吗?
  • 另请参阅此常见问题解答:How can I avoid linker errors with my template classes?
  • @user1698667 我用额外的链接更新了我的答案 - 请阅读这些。与我试图为您写一个完整的答案相比,您最好使用这些详细的解释。 :)
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
相关资源
最近更新 更多