我被c++中的一个模板类卡住了

Im stuck with a template class in c++

本文关键字:一个 c++ 我被      更新时间:2023-10-16

所以我一直在尝试创建一个简单的数组列表类,但一开始就陷入了困境。。。

我的头文件(我删除了.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