2012-11-04 23 views
1

可能重複:
Why do I get 「unresolved external symbol」 errors when using templates?未定義參考`鏈表<int> :: push_front(INT)

LinkedList.h

#ifndef LINKEDLIST_H 
#define LINKEDLIST_H 
#include<iostream> 

template<class T> class LinkedList; 

//------Node------ 
template<class T> 
class Node { 
private: 
    T data; 
    Node<T>* next; 
public: 
    Node(){data = 0; next=0;} 
    Node(T data); 
    friend class LinkedList<T>; 

}; 


//------Iterator------ 
template<class T> 
class Iterator { 
private: 
    Node<T> *current; 
public: 

    friend class LinkedList<T>; 
    Iterator operator*(); 
}; 

//------LinkedList------ 
template<class T> 
class LinkedList { 
private: 
    Node<T> *head; 


public: 
    LinkedList(){head=0;} 
    void push_front(T data); 
    void push_back(const T& data); 

    Iterator<T> begin(); 
    Iterator<T> end(); 

}; 



#endif /* LINKEDLIST_H */ 

LinkedList.cpp

#include "LinkedList.h" 
#include<iostream> 


using namespace std; 

//------Node------ 
template<class T> 
Node<T>::Node(T data){ 
    this.data = data; 
} 


//------LinkedList------ 
template<class T> 
void LinkedList<T>::push_front(T data){ 

    Node<T> *newNode = new Node<T>(data); 

    if(head==0){ 
     head = newNode; 
    } 
    else{ 
     newNode->next = head; 
     head = newNode; 
    }  
} 

template<class T> 
void LinkedList<T>::push_back(const T& data){ 
    Node<T> *newNode = new Node<T>(data); 

    if(head==0) 
     head = newNode; 
    else{ 
     head->next = newNode; 
    }   
} 


//------Iterator------ 
template<class T> 
Iterator<T> LinkedList<T>::begin(){ 
    return head; 
} 

template<class T> 
Iterator<T> Iterator<T>::operator*(){ 

} 

的main.cpp

#include "LinkedList.h" 

using namespace std; 


int main() { 
    LinkedList<int> list; 

    int input = 10; 

    list.push_front(input); 
} 

嗨,我是位於C相當新++,我試圖寫我自己的使用LinkedList的模板。

我跟着我的書非常密切,這就是我得到的。雖然我收到此錯誤。

/main.cpp:18:未定義的引用`鏈表:: push_front(INT)」

我不知道爲什麼,任何想法?

+0

這是通過這裏所描述的相同的問題,因爲這個問題造成的:http://stackoverflow.com/questions/13150412/undefined-symbol-on-a-template-operator-overloading-function – jogojapan

+0

哪本書沒」告訴你,你必須把模板代碼放在頭文件中? – john

回答

5

您正在程序中使用模板。當你使用模板時,你必須把代碼和頭文件寫在同一個文件中,因爲編譯器需要在程序中使用它的地方生成代碼。

你可以做這個或包括#inlcude "LinkedList.cpp"main.cpp

這個問題可以幫助你。 Why can templates only be implemented in the header file?

+0

你不需要將所有內容都放在標題中。您也可以使用顯式實例化。 (並非我建議這樣做。) – jogojapan

+0

包括<刪除線> inlcude theChinmay