首页 > 解决方案 > 如何访问私有指向类

问题描述

我试图学习这个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;
}

标签: c++

解决方案


外面的任何东西LinkedList都不应该知道 aNode是什么。如果你想在列表中插入一些东西,你真的应该只给出你要插入的值。LinkedList 类本身应该负责确定实际需要放置的位置。

因此,您应该有一些只需要一个值的面向公众的函数,例如:

void LinkedList::push_front(int X) {
    insert(head, X); //Insert into the front of the list
}

(也不要忘记insert需要更新head!! 值的边缘情况)


推荐阅读