【问题标题】:C++ Pointer to different class within another classC++ 指向另一个类中不同类的指针
【发布时间】:2017-07-08 22:45:58
【问题描述】:

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

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

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

【问题讨论】:

  • 你知道如何编写非模板链表吗?

标签: c++ class pointers


【解决方案1】:

你需要在linkedList之前为node做一个前向声明:

template <class Type>
struct node;

请查看工作版本here。

【讨论】:

    猜你喜欢
    • 2015-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2013-04-07
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多