难以通过具有两个类和一个 LLL 的头节点

Having difficulty passing in the head node with two classes and a LLL

本文关键字:一个 LLL 节点 两个      更新时间:2023-10-16

我正在尝试将头节点传递给一个递归删除LLL中所有内容的函数。但我不太擅长上课。我有一个用于LLL数据的类称为Node,另一个称为NodeList,用于管理所有节点。

问题是我无法访问私有字段,我不知道如何将它们放入其中。因为我不希望它们像结构一样公开。

C++ 语法有问题,所以一个类可以将数据传递给其他类 我已经检查了这个链接,上面说要确保在 NodeList 类 Node * head 中有一个,但我已经有了。

C++将私有数据传递给类中的其他私有函数 我检查了这个,但对于我所知道的小C++来说,这太过分了。我也认为这只是一个通过引用的问题。

顺便说一下,这不是全部,只是类和一个函数。

class NodeList
{
public:
NodeList();
~NodeList();
//this should delete the whole list
void delList(NodeList * head);
private:
//head
NodeList * head;
};
//this is the nodestructkindathing
class Node
{
public:
Node();
~Node();
private:
//next pointer
Node * next;
int data;
};
void NodeList::delList(NodeList * head)
{
if (!head)
return;
delList(head->next);
delete head;
}

注意:我将类中的 delList 和 Node * head 更改为 NodeList * head,现在我只收到一个错误。

错误:"类节点列表"没有名为"下一步"的成员

正如一些程序员的建议,NodeListNodefriend。当类 A 声明类 B 是朋友时,B 可以看到 A 的私人成员并与之交互。friend船是单向的。除非 B 声明 A 是朋友,否则 A 无法看到 B 的私人成员。

这一更改将解决问题中提出的所有问题。

此代码转储的其余部分是为了使您更轻松地编写链表。链表最好被认为是程序员的成年礼。你会发现你很少在现实生活中使用它们,但它们是CS学生臭名昭著的除草者。实际上,没有人在一两次时就把它们弄对了。它们需要适度的照顾和注意簿记。强烈建议使用纸笔分步绘制列表以及您希望在列表上执行的交互,以帮助可视化和调试链表。

您可能还会发现深入研究指向指针的指针非常有帮助。例如,请参阅此链接答案的"使用指针到指针的替代方法"部分。

在需要的地方嵌入注释。

#include <iostream>
class Node
{
friend class NodeList; // NodeList, and no one else, can now see the private
// members of Node
public:
// Node must be given a value and it not given a next, it's automatically NULL
// this makes it almost impossible to not point link at something useful,
// eliminating the most common of the trivial linked list bugs
Node(int value, Node * link = nullptr);
~Node(); //if it doesn't do anything. Get rid of it. See the Rule of Zero
private:
//next pointer
Node * next;
int data;
};
class NodeList
{
public:
NodeList();
~NodeList();
//this should delete the whole list
void delList(Node * head);
private:
//head
Node * head;
};
Node::Node(int value, Node * link) : next(link), data(value)
{
// test code
std::cout << "Node data = " << data << " next = " << next << 'n';
}
Node::~Node()
{
// test code
std::cout << "~Node data = " << data << 'n';
}

NodeList::NodeList()
{
// test code to give delList something to delete
head = new Node(1,new Node(2,new Node(3)));
}
NodeList::~NodeList()
{
delList(head);
}

//this is the nodestructkindathing
void NodeList::delList(Node * head) // watch out! Parameter head shadows member head!
{
// Warning: This function is recursive and a potential stack-killer if given a 
// long list. Prefer iteration here unless given a reason to do otherwise 
// and guarantees on maximum list length
if (!head)
return;
delList(head->next);
delete head;
}
int main()
{
NodeList test;
}

预期产出:

Node data = 3 next = 0
Node data = 2 next = 0x2ec6cc0
Node data = 1 next = 0x2ec6ce0
~Node data = 3
~Node data = 2
~Node data = 1

讨论三、五和零规则。如果您想要一个稳定的链表或C++编写非平凡系统,那么了解这些规则是必须的。

关于friend的文档 .