【问题标题】:Building a Iterator class for linked list (Error: no matching constructor for initialization)为链表构建迭代器类(错误:没有匹配的初始化构造函数)
【发布时间】:2019-04-30 11:40:07
【问题描述】:

在函数“迭代列表::begin()”中{ 这个迭代(头)有一个问题“没有匹配的初始化构造函数”。 head 是一个节点指针,我为它构建了一个构造函数。不知道是什么问题。

List.h

#include "Iteratoring.h"
struct Node {
    int data;       // value in the node
    Node *next;  //  the address of the next node

    /**************************************
            **      CONSTRUCTOR    **
    ***************************************/
    Node(int data) : data(data), next(0) {}
};
class List {
private:
    Node *head= nullptr;          // head node
    Node *tail;          // tail node
    Iteratoring begin();
public:
};

List.cpp

#include "List.h"

Iteratoring List::begin() {
    return Iteratoring(head);   //The error is here. no matching constructor for initialization
}

Iteratoring.h

#include "List.h"

class Iteratoring {
private:
    Node *current;
public:
    Iteratoring(){
        current= nullptr;
    };

    Iteratoring(Node *ptr){
        current=ptr;
    };

};

【问题讨论】:

  • 这是标准的循环依赖问题:文件List.h包含Iteratoring.h,其中包含List.h。您可以通过前向声明解决这个问题(我的建议是在Iteratoring.h 文件中使用Node 的前向声明,并删除包含List.h)。

标签: c++ linked-list iterator


【解决方案1】:

这是一个循环依赖问题。在Iteratoring.h 中有#include "List.h",在List.h 中有#include "Iteratoring.h"

您应该改用forward declaration。例如

Iteratoring.h

class Node;
class Iteratoring {
private:
    Node *current;
public:
    Iteratoring(){
        current= nullptr;
    };

    Iteratoring(Node *ptr){
        current=ptr;
    };

};

【讨论】:

  • 谢谢。你从哪里学来的这个?我的学校从来没有教过我这个。
  • @Mr.Java 来自 books 和 cppreference.com。
  • @Mr.Java 学校通常会错过很多 C++ 教学。这也是一个经验问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
  • 2015-07-28
  • 1970-01-01
相关资源
最近更新 更多