2013-10-04 74 views
-1
//includes, using etc. 
int main() 
{ 
    List<int> a; 
    cout << a.size() << endl; 
    return 0; 
} 


//list.h 
template <class T> 
class List{ 

int items; 

public: 
List(); 
~List(); 

int size() const; 

}; 

//list.cpp 
#include "list.h" 
template<class T> 
List<T>::List() : 
items(0) 
{} 

template<class T> 
List<T>::~List() 
{} 

template<class T> 
int List<T>::size() const 
{ return items; } 

這應該工作,不應該嗎?當我在主函數上面定義list.h和list.cpp的內容時,一切正常。然而,這給了我一些錯誤:C++模板 - 未定義的參考

main.cpp:(.text+0x12): undefined reference to List<int>::List()'
main.cpp:(.text+0x1e): undefined reference to
List::size() const'
main.cpp:(.text+0x4f): undefined reference to List<int>::~List()'
main.cpp:(.text+0x64): undefined reference to
List::~List()'

,當我在主函數改變List<int> a;List<int> a();我得到的唯一錯誤是這樣的:

main.cpp:10:12: error: request for member ‘size’ in ‘a’, which is of non-class type ‘List()’

幫助我,有什麼不對?

+0

請參閱http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Jarod42

+0

模板必須定義和實現必須在一個文件中。 – andre

回答

1

List是一個模板類和(大部分時間)這意味着它的代碼必須在頭文件中。

此外,

List<int> a(); 

一個名爲a函數返回一個List<int>的聲明。我強調:a不是List<int>類型的默認初始化對象。

+0

謝謝!!!! '必須在頭文件中'救了我的命! – gone