2011-12-20 38 views
1

我剛開始使用模板。構造函數鏈接器錯誤使用模板

我想創建一個鏈接列表類,它存儲類型的地址(可能是一個對象)。這裏是我的項目的佈局:

linkedlist.h 
node.h 
node.cpp 
linkedlist.cpp 
main.cpp 

Node.h

template <class Type> struct Node 
{ 
public: 
    Node<Type>(); 
    Node<Type>(Type* x = 0, Node* pNext = 0); 
    Type* data; 
    Node* next; 
}; 

Node.cpp

#include "node.h" 

template<class Type> Node<Type>::Node() 
{ 
    next = 0; 
    data = 0; 
} 
template<class Type> Node<Type>::Node(Type* item, Node* ptrNext) 
{ 
    next = ptrNext; 
    data = item; 
} 

linkedlist.h

#include "node.h" 

template <class Type> class LinkedList 
{ 
private: 
    Node<Type>* root; 

public: 
    LinkedList<Type>(); 
    ~LinkedList<Type>(); 
    void insert(Type*); 
    void remove(Type*); 
}; 

linkedlist.cpp

#include "linkedlist.h" 

template <class Type> LinkedList<Type>::LinkedList() 
{ 
    root = 0; 
} 

template <class Type> LinkedList<Type>::~LinkedList() 
{ 
    Node* p; 
    while(p = root) 
    { 
     root = p->next; 
     delete p; 
    } 
} 
// many more.... 

在main.cpp中,我有以下幾點:

int main() 
{ 
    int *ptrA, *ptrB; 
    int a = 100, b = 10; 

    ptrA = &a; 
    ptrB = &b; 

    LinkedList<int>myList; 
    myList.insert(ptrA); 
    return 0; 
} 

和編譯器扔連接錯誤:

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::~LinkedList<int>(void)" ([email protected]@@[email protected]) referenced in function _main 
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall LinkedList<int>::insert(int *)" ([email protected][email protected]@@[email protected]) referenced in function _main 
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::LinkedList<int>(void)" ([email protected]@@[email protected]) referenced in function _main 

嘗試的解決方案:

我改稱爲LinkedListmyList()。這可以解決鏈接器錯誤,但我將無法調用任何成員函數。

如果我放(),myList.insert(ptrA)會說「錯誤:表達式必須有一個類類型」。

很明顯,這是行不通的。

有什麼問題?我認爲整個實施有問題....

感謝您的時間。

+1

可能的重複[爲什麼模板只能在頭文件中實現?](http://stackoverflow.com/questions/495021/why-can-templates-only - 在頭文件中實現) – Flexo 2011-12-20 02:08:32

+0

或http://stackoverflow.com/questions/3705740/c-lnk2019-error-unresolved-external-symbol-template-classs-constructor-and或http:/ /stackoverflow.com/questions/3680312/linker-error-lnk2019 – Flexo 2011-12-20 02:09:55

+0

看起來像一個家庭作業。什麼編譯器? – Geoffroy 2011-12-20 02:10:05

回答

3

從linkedlist.cpp移動的東西..到linkedlist.h

,因爲它的聲明「作出代碼模板」機器代碼實際上並不存在,直到你給編譯器要使用的類型。

例如,只要編譯器可以看到所有的模板代碼,只要你去:LinkedList<int>myList編譯器創建一個實體類,它可以創建一個int整數的鏈表。就你而言,編譯器無法看到模板代碼,所以無法生成機器代碼。


在C++ 11

你可以說「的extern模板」:http://en.wikipedia.org/wiki/C%2B%2B11#Extern_template

在頭文件

,然後實現在linkeList.cpp文件中的「廉政」版本..它會它在嘗試使用main.cpp時可用。

這給了編譯器無需在每一箇中都生成機器碼的優點。使用模板的cpp文件,並且使編譯速度更快。

它也可以在C++ 98中完成..但它有點棘手,並不是100%可移植,因爲我理解它..更容易在任何地方生成代碼。 gnu gcc:http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html

+0

非常感謝。你剛剛救了我幾個小時的頭撞! – 2017-05-31 17:31:18

相關問題