C++模板 - 未定义的引用

C++ Templates - undefined reference

本文关键字:引用 未定义 模板 C++      更新时间:2023-10-16
//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 的内容时,一切正常。但是,这给了我一些错误:

main.cpp:(.text+0x12): 对List<int>::List()'
main.cpp:(.text+0x1e): undefined reference to
List::size() const'
的未定义引用 main.cpp:(.text+0x4f): 对List<int>::~List()'
main.cpp:(.text+0x64): undefined reference to
List::~List()' 的未定义引用

当我更改主函数中的List<int> a;List<int> a();时,我得到的唯一错误是:

主.cpp:10:12:错误:请求"a"中的成员"大小",即 非类类型"列表()"

帮帮我,怎么了?

List是一个

模板类,(大多数时候)这意味着它的代码必须位于头文件中。

另外

List<int> a();

是返回List<int>的名为 a 的函数的声明。我强调:a不是类型 List<int> 的默认初始化对象。