2013-10-04 59 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