C++ 指向另一个类中的不同类的指针

C++ Pointer to different class within another class

本文关键字:同类 指针 另一个 C++      更新时间:2023-10-16

我一直在搜索文档并检查我的类给出的示例代码,但无法弄清楚这里出了什么问题。我正在尝试构建一个链表结构,需要可以指向节点但似乎无法正确初始化它们的指针。节点相互指向很好,是带有第一个/最后一个/当前指针的总体类给我带来了问题。

当我尝试创建节点类的指针时,下面的代码给了我一堆错误。我在第 19、20 和 21 行收到 C2238"';"前面的意外标记",以及 C2143"在"*"之前缺少';"和 C4430"缺少类型说明符..."同样是第 19、20 和 21 行(linkedList 的受保护部分(。

template <class Type>
class linkedList
{
public:
//constructors
linkedList();
//functions
void insertLast(Type data);             //creates a new node at the end of the list with num as its info
void print();                           //steps through the list printing info at each node
int length();                           //returns the number of nodes in the list
void divideMid(linkedList sublist);     //divides the list in half, storing a pointer to the second half in the private linkedList pointer named sublist
//deconstuctors
~linkedList();
protected:
node *current;                          //temporary pointer
node *first;                            //pointer to first node in linked list
node *last;                             //pointer to last node in linked list
bool firstCreated;                      //keeps track of whether a first node has been assigned
private:
};
template <class Type>
struct node
{
Type info;
node<Type> *next;
};

按如下所示更改受保护部分也会留下 C2238 和 C4430 错误,但将 C2143 更改为"<"之前缺少';">

"
node<Type> *current;                            //temporary pointer
node<Type> *first;                              //pointer to first node in linked list
node<Type> *last;                               //pointer to last node in linked list

您需要在linkedList之前为node进行前向声明:

template <class Type>
struct node;

请在此处查看工作版本。