2011-04-27 102 views
0

Possible Duplicate:
Undefined reference error for template methodC++模板錯誤

你好,我有這樣的代碼是給我這個錯誤:

未定義的參考`MyStack ::推(INT)」的main.cpp

爲什麼?

MyStack.h:

#ifndef STACK_H 
#define STACK_H 

template <typename T> 
class MyStack 
{ 
private: 
    T *stack_array; 
    int count; 

public: 
    void push(T x); 
    void pop(T x); 

    void xd(){} 
}; 

#endif /* STACK_H */ 

MyStack.cpp:

#include "mystack.h" 

template <typename T> 
void MyStack<T>::push(T x) 
{ 
    T *temp; 
    temp = new T[count]; 

    for(int i=0; i<count; i++) 
     temp[i] = stack_array[i]; 

    count++; 

    delete stack_array; 
    stack_array = new T[count]; 

    for(int i=0; i<count-1; i++) 
     stack_array[i] = temp[i]; 
    stack_array[count-1] = x; 
} 

template <typename T> 
void MyStack<T>::pop(T x) 
{ 

} 

main.cpp中:

#include <iostream> 

#include "mystack.h" 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    MyStack<int> s; 
    s.push(1); 
    return 0; 
} 
+1

順便說一句,你還需要在構造函數中可能使用它之前,你的初始化計數變量。 – 2011-04-27 09:16:46

+0

謝謝!我確實注意到需要初始化,但是我想解決這個問題非常糟糕,因爲它讓我感到不安,哈哈。 – petermlm 2011-04-27 12:49:00

回答

3

類模板成員的定義必須在相同的文件,但您已將其定義在不同的文件中(MyStack.cpp)。

簡單的解決辦法是,在最後以下行添加到您的MyStack.h文件:

#include "MyStack.cpp" // at the end of the file 

我知道這是.cpp文件,但將解決您的問題。

也就是說,你MyStack.h應該是這樣的:

#ifndef STACK_H 
#define STACK_H 

template <typename T> 
class MyStack 
{ 
private: 
    T *stack_array; 
    int count; 

public: 
    void push(T x); 
    void pop(T x); 

    void xd(){} 
}; 

#include "MyStack.cpp" // at the end of the file 

#endif /* STACK_H */ 

如果這樣做,則不需要在MyStack.cpp#include "mystack.h"了。你可以刪除它。

+1

謝謝!我只是寫在.h文件中的一切,哈哈! – petermlm 2011-04-27 12:50:00

2

您必須將您的模板類聲明和實現放在頭文件中,因爲在編譯時實例化模板時編譯器需要了解模板實現。試着把執行MyStack裏面MyStack.h

你可以找到更詳細的解釋here。只需轉到文章開頭的「模板和多文件項目」。