【问题标题】:How do I write a public function to return a head pointer of a linked list?如何编写一个公共函数来返回链表的头指针?
【发布时间】:2009-12-12 11:19:40
【问题描述】:
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 函数声明中的 '*' 之前(是的,我想不出更好的名字)。这个函数的目的是返回头指针。

【问题讨论】:

  • 好的,我知道了。我只是交换了私有和公共块。谢谢大家!
  • 请注意,您可以拥有多个私有/受保护/公共块。

标签: c++ struct linked-list


【解决方案1】:

在使用之前声明节点。

【讨论】:

    【解决方案2】:

    你必须在 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;
    
    };
    

    【讨论】:

    • 有没有办法通过保持结构私有来做到这一点?
    • Brandon> 你可以只声明结构,添加一个答案来说明如何。
    【解决方案3】:

    回答 Brandon 关于将结构保持私有,或在添加声明时保留当前代码的方法是:

    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;
    
    };
    

    【讨论】:

      【解决方案4】:
      Node * getHead()
      

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

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

      在使用之前先放上Node的定义。

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

      【讨论】:

        【解决方案5】:

        另一种方法是通过在Node 之前放置struct 来转发声明Node

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

        【讨论】:

          猜你喜欢
          • 2016-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-12
          • 2012-03-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多