繁体   English   中英

如何编写公共函数以返回链接列表的头指针?

[英]How do I write a public function to return a head pointer of a linked list?

class Newstring
{
public:
    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;

};

我收到语法错误:缺少';' getHead函数的声明的“ *”之前 (是的,我想不出更好的名字了)。 该函数的目的是返回头指针。

在使用它之前声明节点。

您必须在getHead()之上声明Node结构。

class Newstring
{

public:
    struct Node
    {
        char item;
        Node *next; 
    };
    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:

    Node *head;

};

要回答布兰登有关将结构私有化或在添加声明时保留当前代码的方法,方法是:

class Newstring
{
    struct Node; // here the declaration
public:

    Newstring();
    void inputChar ( char);
    void display ();
    int length ();
    void concatenate (char);
    void concatenate (Newstring);
    bool substring (Newstring);
    void createList ();
    Node * getHead (); // error
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;

};
Node * getHead()

遇到getHead()时,编译器无法获取Node的定义。

  struct Node
    {
        char item;
        Node *next; 
    };

在使用节点之前将其定义。

class Newstring
{
private:
    struct Node
    {
        char item;
        Node *next; 
    };
    Node *head;
public:
    Newstring(); ...
    Node * getHead (); 

另一种方式是转发申报Node放置一个struct之前, Node

    :
    void createList ();
    struct Node * getHead ();
private:
    struct Node
    {
        :

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM