我收到编译器错误:错误“节点”未命名类型。 这是我的标题:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
template <class ItemType>
class LinkedList
{
public:
LinkedList(); // Constructor
bool isEmpty() const; // Checks if list is empty.
int getLength() const; // Returns the amount of times in the list.
bool insert(int index, const ItemType& insertItem); // Inserts an item at index.
bool remove(int index); // Removes item at index.
void clear(); // "clears" the list, but actually sets amount of items to zero.
ItemType getIndex(int index); // Returns the item at a given index.
int find(const ItemType& findItem); // Finds an item, then returns the index it was found.
void printList() const;
private:
struct Node // Struct so I can have my linked list.
{
ItemType item; // Data item.
Node* next; // Pointer to the next node.
};
int itemCount; // Current amount of items in list.
Node* headPtr; // Head/beginning of the list.
Node* getNodeAt(int position) const; // Private method to get position.
};
#include "LinkedList.cpp"
#endif // LINKEDLIST_H
然后我的cpp:
#include "LinkedList.h"
#include <iostream>
using namespace std;
// All the other methods, and at the very end...
template<class ItemType>
Node* LinkedList<ItemType>::getNodeAt(int position) const //Error is here.
{
Node* retPtr = headPtr;
int index = 0;
while(index != position)
{
retPtr = retPtr->next;
index++;
}
return retPtr;
}
错误出在 getNodeAt 的 cpp 文件中的方法签名处。从我读到的内容来看,当引用一个尚 undefined object 时,似乎会出现错误,但我并没有真正看到我是如何犯下这个错误的。
最佳答案
错误正确:不存在Node
在程序中的任意位置键入。但是有一个 LinkedList<ItemType>::Node
类型。改用它。
另一个问题:你不应该包括LinkedList.cpp
在LinkedList.h
.当然你不应该包括LinkedList.h
在LinkedList.cpp
如果你包含 .cpp
文件。一般的做法是在 header 中实现所有的模板代码。如果您想分离实现并将其包含在 header 中,则不要在实现中包含 header 并为其提供与源代码扩展不同的扩展,以免混淆构建系统。
关于c++ - 错误没有命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645122/