C++ LinkedList非模板错误求助:模板链表代码报错排查
解决"LinkedList is not a template"编译错误
在实现模板链表时遇到编译错误:LinkedList is not a template,相关代码如下:
LinkedList.h
#ifdef LINKED_LIST_ #define LINKED_LIST_ #include "ListInterface.h" #include "Node.h" template<class ItemType> class LinkedList : public ListInterface<ItemType> { private: Node<ItemType>* headPtr; int itemCount; Node<ItemType>* getNodeAt (int postion) const; public: LinkedList(); LinkedList(const LinkedList<ItemType>& aList); virtual ~LinkedList(); bool isEmpty() const; int getLength() const; bool remove(int postion); void clear(); ItemType getEntry(int position) const; ItemType replace(int position, const ItemType& newEntry); }; #include "LinkedList.cpp" #endif
LinkedList.cpp
#include "LinkedList.h" #include <iostream> using namespace std; template<class ItemType> LinkedList<ItemType>::LinkedList() : headPtr(nullptr), itemCount(0){ } template<class ItemType> LinkedList<ItemType>::~LinkedList(){ }
错误原因分析
这个错误的核心是模板类的实现文件被单独编译导致的冲突:
你采用了模板类常用的「将实现包含到头文件」的写法(在LinkedList.h末尾包含LinkedList.cpp),但如果编译命令中同时把LinkedList.cpp作为单独的编译单元处理,编译器在编译该.cpp文件时,会先包含LinkedList.h,此时模板类的定义已经被处理,当解析到LinkedList<ItemType>::时,会错误地认为LinkedList不是模板类,从而抛出该错误。
解决方案
- 禁止单独编译LinkedList.cpp:只编译包含LinkedList.h的主程序文件即可,因为头文件已经把实现内容包含进来,单独编译.cpp会引发重复定义和识别错误。
- 修改实现文件后缀:将LinkedList.cpp重命名为LinkedList.inl(inline文件的标准后缀),然后在LinkedList.h末尾改为
#include "LinkedList.inl",这样能更清晰地标识这是模板的内联实现部分,避免误编译。 - 额外检查:确认头文件保护宏
LINKED_LIST_没有被其他文件重复定义,不过从代码来看这个宏命名合理,大概率不是问题根源。
注:你的LinkedList拷贝构造函数目前只有声明没有实现,后续需要补充以避免潜在的内存问题,但这不是当前编译错误的原因。
内容的提问来源于stack exchange,提问作者Dylan
相关产品推荐
相关产品推荐

