2012-05-03 2 views
2

Можно создать дубликат:
Why can templates only be implemented in the header file?
“Undefined symbols” linker error with simple template classОШИБКА LNK2019 ФАТАЛЬНАЯ ОШИБКА С

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 
} 

main.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: неразрешенный внешний символ "общественность: недействительная очередь __thiscall :: толчок (INT)" (? Толчок @ $ очередь @ H @@ QAEXH @ Z?) Ссылка в функции _MAIN 1> main.obj: ошибка LNK2019: неразрешенный внешний символ "public: __thiscall queue :: queue (int)" (? 0? $ Queue @ H @@ QAE @ H @ Z), на который ссылается функция _main 1> c : \ пользователи \ ПК \ документы \ Visual Studio 2010 \ Projects \ lab10 \ Debug \ lab10.exe: фатальная ошибка LNK1120: 2 неразрешенные внешние

EDIT: Решение приведено в here.

+0

Как вы компиляции это? – robert

+0

http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file, возможно, было лучше – Flexo

ответ

0

Классы шаблонов не могут быть разделены на .cpp и .h файлы, потому что компилятор требует копию реализации, чтобы сгенерировать желаемый класс из шаблона.

Вы должны переместить содержимое queue.cpp в queue.cpp

Смежные вопросы