C++模板 - 未定义的引用
C++ Templates - undefined reference
//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()'
List::size() const'
main.cpp:(.text+0x1e): undefined reference to
的未定义引用 main.cpp:(.text+0x4f): 对List<int>::~List()'
List::~List()' 的未定义引用
main.cpp:(.text+0x64): undefined reference to
当我更改主函数中的List<int> a;
以List<int> a();
时,我得到的唯一错误是:
主.cpp:10:12:错误:请求"a"中的成员"大小",即 非类类型"列表()"
帮帮我,怎么了?
List
是一个模板类,(大多数时候)这意味着它的代码必须位于头文件中。
另外
List<int> a();
是返回List<int>
的名为 a
的函数的声明。我强调:a
不是类型 List<int>
的默认初始化对象。
相关文章:
- 编译C++时未定义的引用
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 未定义的引用在哪里
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 对 Scalar ::Scalar() 的未定义引用
- 已定义函数时出现 G++ "未定义的引用"错误
- 链接 cmake 时出现未定义的引用错误
- 对复制 CTOR 和 CTOR 的未定义引用
- 错误:未定义对'oboe::AudioStreamBuilder::openStream(oboe::AudioStream**)'的引用
- 右值引用未定义的行为
- 对"vtable for DigitalClock"的未定义引用 - 未定义对"DigitalClock::staticMetaObject"的引用 - Qt
- 函数类型到函数类型的引用:未定义的引用
- avcodec_alloc_context引用未定义,但ffmpeg链接顺序正确
- 从c++调用Fortran子程序,链接时引用未定义
- 枚举引用未定义,但位于包含的头文件中