c++ - 如何访问私有指向类
问题描述
我试图学习这个linkedList Stack ADT的东西,我初始化了空头并尝试向其中添加一个节点。但由于“Node* head”是私有的,我无法访问它。我知道我必须更改其类型说明符,但我有一个需要保密的作业。另外,当我公开时,我无法进行任何更改,并且出现异常抛出错误,该错误为空。这是代码(代码是从讲座幻灯片中复制的,我只添加了主代码):
#include <iostream>
using namespace std;
class Node {
public:
Node(int);
int data;
Node* next;
};
Node::Node(int x){
data = x;
}
class LinkedList {
public:
LinkedList();
void insert(Node*, int);
void printList();
~LinkedList();
private:
Node* head;
};
LinkedList::LinkedList() {
head = 0;
}
void LinkedList::printList() {
Node* n = head;
while (n != 0) {
cout << n->data;
n = n->next;
}
}
void LinkedList::insert(Node* current, int X) {
Node* xNode = new Node(X);
xNode->next = current->next;
current->next = xNode;
}
LinkedList::~LinkedList() {
Node* dNode = head;
while (dNode != 0) {
head = head->next;
delete dNode;
dNode = head;
}
}
int main() {
LinkedList *list = new LinkedList();
list->insert(//whatShouldIdoHere, 5);
list->printList();
return 0;
}
解决方案
外面的任何东西LinkedList
都不应该知道 aNode
是什么。如果你想在列表中插入一些东西,你真的应该只给出你要插入的值。LinkedList 类本身应该负责确定实际需要放置的位置。
因此,您应该有一些只需要一个值的面向公众的函数,例如:
void LinkedList::push_front(int X) {
insert(head, X); //Insert into the front of the list
}
(也不要忘记insert
需要更新head
!! 值的边缘情况)
推荐阅读
- python - python hlookup查找函数
- powershell - Microsoft ADFS with Powershell - 使用安全哈希算法 SHA-1 添加依赖方信任
- java - 字符串到 JSON 的 ArrayList
- c - 函数中的指针数组未显示在调用中使用的数组的正确值上
- javascript - 用于检索数据的 Web API
- javascript - 反应模式没有得到显示
- cloudera - Cloudera Mesos - 当 mesos-slave 停止时,当前作业处于“丢失”状态
- c# - Winform mssql多表更新c#
- python - 使用 configparser 解析 ini 文件会给出 configparser.MissingSectionHeaderError 与 'ÿþ\n' 作为第一行
- c# - 绑定“找不到 CLR 属性”时出现 Avalonia UI 错误