2

重複の可能性:
テンプレートをヘッダーファイルにのみ実装できるのはなぜですか?
単純なテンプレートクラスでの「未定義のシンボル」リンカエラー

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:未解決の外部シンボル "public:void __thiscall queue :: push(int)"(?push @?$ queue @ H @@ QAEXH @ Z)関数_main 1> main.objで参照:エラーLNK2019:未解決の外部シンボル "public:__thiscall queue :: queue(int)"(?? 0?$ queue @ H @@ QAE @ H @ Z)は関数_main 1> c:\ users \ pc \documents\で参照されていますvisual studio 2010 \ Projects \ lab10 \ Debug \ lab10.exe:致命的なエラーLNK1120:2つの未解決の外部

編集:解決策はここにあります。

4

2 に答える 2

0

コンパイラはテンプレートから目的のクラスを生成するために実装のコピーを必要とするため、テンプレートクラスを.cppファイルと.hファイルに分離することはできません。

queue.cppの内容をqueue.cppに移動する必要があります

于 2012-05-03T18:51:17.113 に答える
0

テンプレートに関連するすべてのキューの実装をヘッダーファイルに入れます。ちょうど同じように:なぜテンプレートはヘッダーファイルにのみ実装できるのですか?

于 2012-05-03T18:41:55.340 に答える