【问题标题】:ERROR LNK2019 FATAL ERROR C [duplicate]错误 LNK2019 致命错误 C [重复]
【发布时间】:2012-05-03 18:38:03
【问题描述】:

可能重复:
Why can templates only be implemented in the header file?
“Undefined symbols” linker error with simple template class

queue.h

#include<iostream>
using namespace std;

template <class t>
class queue {  

    public:  
        queue(int=10);  
        void push(t&);  
        void pop();  
        bool empty();    

    private:  
        int maxqueue;  
        int emptyqueue;  
        int top;  
        t* item;  
};  

queue.cpp

#include<iostream>

#include"queue.h"
using namespace std;

template <class t>
queue<t>::queue(int a){
    maxqueue=a>0?a:10;
    emptyqueue=-1;
    item=new t[a];
    top=0;
}

template <class t>
void queue<t>::push(t &deger){

    if(empty()){
        item[top]=deger;
        top++;
    }
    else
        cout<<"queue is full";
}
template<class t>
void queue<t>::pop(){
    for(int i=0;i<maxqueue-1;i++){
        item[i]=item[i+1];
    }
    top--;
    if(top=emptyqueue)
        cout<<"queue is empty";
}
template<class t>
bool queue<t>::empty(){
    if((top+1)==maxqueue)
        return false
    else
        return true 
}

ma​​in.cpp

#include<iostream>
#include<conio.h>

#include"queue.h"
using namespace std;

void main(){
    queue<int>intqueue(5);
    int x=4;
    intqueue.push(x);

    getch();
}

我已经使用模板创建了队列。编译器给出了这个错误。我无法解决这个问题。

1>main.obj:错误 LNK2019:函数 _main 中引用的未解析外部符号“public:void __thiscall queue::push(int)”(?push@?$queue@H@@QAEXH@Z) 1>main.obj:错误 LNK2019:函数 _main 中引用的未解析外部符号“public:__thiscall queue::queue(int)”(??0?$queue@H@@QAE@H@Z) 1>c:\users\pc\documents\visual studio 2010\Projects\lab10\Debug\lab10.exe : 致命错误 LNK1120: 2 unresolved externals

编辑:here 中给出了解决方案。

【问题讨论】:

标签: c++


【解决方案1】:

将所有模板相关的队列实现放在头文件中。就像:Why can templates only be implemented in the header file?

【讨论】:

    【解决方案2】:

    模板类不能分为 .cpp 和 .h 文件,因为编译器需要实现的副本才能从模板生成所需的类。

    需要将queue.cpp的内容移动到queue.cpp中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多