可能重複:
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)」
我不知道爲什麼,任何想法?
這是通過這裏所描述的相同的問題,因爲這個問題造成的:http://stackoverflow.com/questions/13150412/undefined-symbol-on-a-template-operator-overloading-function – jogojapan
哪本書沒」告訴你,你必須把模板代碼放在頭文件中? – john