2011-02-09 8 views
0

コンパイラは私にこれらのエラーを与えます。それは私には何の問題も動作しないはずのようにそれはそう...私はこれが動作しない理由はわかりませんスタックリンク・エラー・質問

/* 
* Stack.h 
* Stack 
* 
* Created by Sterling McLeod on 2/1/11. 
* Copyright 2011 University of North Carolina at Charlotte. All rights reserved. 
* 
*/ 
#ifndef STACK_H 
#define STACK_H 

#include <exception> 

template<typename T> 
class Stack { 

public: 


    class EmptyTreeException : public std::exception { 
    public: 
     virtual const char* what() const throw(); 
    }; //end exception 



    Stack(); 
    ~Stack(); 

    T peek(); 
    bool isEmpty(); 
    int size(); 

    void push(T&); 
    T pop(); 

private: 
    T* top; 
    int count; 
}; 
#endif STACK_H 
[/code] 
[code] 
/* 
* Stack.cpp 
* Stack 
* 
* Created by Sterling McLeod on 2/1/11. 
* Copyright 2011 University of North Carolina at Charlotte. All rights reserved. 
* 
*/ 

#include "Stack.h" 

template <typename T> 
const char* Stack<T>::EmptyTreeException::what() const throw() { 
    return "The stack is empty!\n"; 
} 


template <typename T> 
Stack<T>::Stack() : count(0) {} 
template <typename T> 
Stack<T>::~Stack() {delete [] top;} 


template <typename T> 
T Stack<T>::peek() {return top[count];} 

template <typename T> 
bool Stack<T>::isEmpty() {return count == 0;} 

template <typename T> 
int Stack<T>::size() {return count;} 




template <typename T> 
void Stack<T>::push(T& n) { 
    top[++count] = n; 
} //END PUSH 


template <typename T> 
T Stack<T>::pop() { 
    if(isEmpty()) 
     throw EmptyTreeException(); 
    T result = top[count]; 
    top[count--] = NULL; 
    return result; 
} //END POP 
[/code] 
[code] 
#include <iostream> 
#include "Stack.h" 

int main (int argc, char * const argv[]) { 
    Stack<int> s; 
    int a = 10; 
    while(a < 50) { 
     s.push(a); 
     a += 10; 
    } //end 
    return 0; 
} 

-

コードは次のようです。誰かが私に偉大なヒントを与えることができれば。ありがとう。

+0

[C++ STLコード全体が.cpp/.cファイルではなく.hに含まれる理由は何ですか?](http://stackoverflow.com/questions/1733112/what-is) -c-st-code-to-the-h-than-th-in-the-h-than-th-を含む理由) –

+0

これは実行時ではなく、リンク時です。 – Puppy

答えて

6

要するに、テンプレート定義をヘッダファイルに入れる必要があります。そうしないと、コンパイラはインスタンス化せず、リンカは泣きます。

詳細については、http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12を参照してください。