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

时间:2017-07-08 22:45:59

标签: c++ class pointers

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

当我尝试编写节点类的指针时,下面的代码给了我一堆错误。我得到了C2238"之前的意外标记''"在第19,20和21行以及C2143"缺少&#39 ;;'之前' *'"和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更改为&#34;缺少&#39 ;;&#39;之前&#39;&lt;&#39;&#34;

    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

1 个答案:

答案 0 :(得分:1)

您需要在node

之前为linkedList发出前瞻性声明
template <class Type>
struct node;

请参阅工作版here