【问题标题】:How to create a constructor of linked list for iterator class in c++?如何在 C++ 中为迭代器类创建链表的构造函数?
【发布时间】:2020-11-13 16:45:11
【问题描述】:

当我尝试运行此代码时,出现此错误:

'Linkedlist' 的构造函数必须显式初始化成员 'point' 没有默认构造函数 链表::链表()

class Node {
    public:
        Node* next;
        Node* prev;
        Elem elem;
        friend class Linkedlist;
        Node(): next(NULL), prev(NULL)
        {}
        Node(Elem elem) : elem(elem)
        {}
};

class Iterator {
private:
    Node* iter;
    //Iterator(Node curr);
public:
    friend class Linkedlist; 
    Iterator(Node* curr) {
        iter=curr;
    } 
};

class Linkedlist { 
private:
    Node *head;
    Node *tail;
    int N;
    Iterator point;
public:
    Iterator point;
    Linkedlist();
};

Linkedlist::Linkedlist() {
    N = 0;
    head = new Node();
    tail  = new Node();
    head->next = tail;
    tail->prev = head;
    point.iter = head;
}

我不知道如何解决这个问题,感谢任何帮助!

【问题讨论】:

  • 您的Iterator 类应该维护一个Node* currentNode; 成员变量,而不是Node iter;
  • 其实有 * 但不知怎么没有出现,所以我编辑了
  • iter 仍然是一个令人困惑的名称,而且整个 Iterator 类定义应该是 LinkedList 的嵌套类。
  • LinkedList 的构造函数没有构造迭代器点,因此编译器尝试使用不存在的默认构造函数来构造它。要么添加一个,要么显式初始化它。
  • 你需要在链表构造函数中添加对点构造函数的调用

标签: c++ doubly-linked-list


【解决方案1】:

您可以做几件事。您可以将其声明为指针

class Linkedlist { //Missing a c on your class declaration
    private:
        Node *head;
        Node *tail;
        int N;
        //Iterator point; (You have this declared twice)


    public:
        Iterator *point;
        Linkedlist();//s

在这种情况下,您需要像这样调用 LinkedList 构造函数中的点构造函数。

Linkedlist::Linkedlist() {
        N = 0;

        head = new Node();
        tail  = new Node();
        head->next = tail;
        tail->prev = head;
        point = new Iterator(head); // Use the existing constructor
}

或者,您可以为 Iterator 类创建一个默认构造函数。

class Iterator {
           private:
               Node* iter;
           public:
               friend class Linkedlist;
               Iterator() {
                   iter = 0;
               }
               Iterator(Node* curr) {
                    iter=curr;
               } 
        };

最后,您可以使用这种语法指示程序在为 LinkedList 分配内存之前使用空指针分配点。

Linkedlist::Linkedlist() : point(0) {
        N = 0;

        head = new Node();
        tail  = new Node();
        head->next = tail;
        tail->prev = head;
        point.iter=head;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 2020-08-01
    • 2014-11-10
    • 2011-12-10
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多