我被c++中的一个模板类卡住了
Im stuck with a template class in c++
所以我一直在尝试创建一个简单的数组列表类,但一开始就陷入了困境。。。
我的头文件(我删除了.cpp文件,仍然得到了相同的消息)
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;
template <typename T>
class ArrayList {
private:
T *arr;
int length;
public:
ArrayList();
void Insert(T item);
void Print();
//friend &ostream operator<< (ostream &out, ArrayList &al);
};
#endif
和我的错误
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall ArrayList<int>::ArrayList<int>(void)" (??0?$ArrayList@H@@QAE@XZ) referenced in function _main
1>C:UsersGannashDesktopProgrammingC++WSXMLReaderDebugXMLReader.exe : fatal error LNK1120: 1 unresolved externals
这就像你只声明了类的方法,而没有定义它们
将所有定义放在标题中
如果您正在定义一个模板类,您应该以内联方式提供所有成员函数implemententations。缺失的ctor肯定是一个公认的问题,但当您实际使用类时,还会出现其他问题。此外,还有一些标准容器可以提供您可能想要实现的内容,尤其是std::vector。
此外,在头文件中使用名称空间是禁止的(或者至少非常不鼓励)您应该使用std::qualification,尤其是只需要一次。
您尚未在.cpp文件中定义ArrayList()、Insert()和Print()。您需要为这些函数编写代码,或者将它们转换为纯虚拟函数,也称为virtual Print()=0;
让我们剖析错误消息:
unresolved external symbol "public: __thiscall ArrayList<int>::ArrayList<int>(void)" (??0?$ArrayList@H@@QAE@XZ) referenced in function _main
unresolved external symbol
=>声明了一些符号(此处为函数),但未定义
ArrayList<int>::ArrayList<int>(void)
=>使用T=int 实例化的构造函数或ArrayList类模板
referenced in function _main
=>可能在main()中有如下代码:
ArrayList<int> IntList;
解决方案是提供构造函数的实现,可能是:
ArrayList() : arr( 0 ), length( 0 ) {}
在班级内部。
BTW,请随时查看以下内容供您参考:
std::array
std::vector
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '