如何使用指针数组实现节点

How to implement a node with an array of pointers?

本文关键字:实现 节点 数组 指针 何使用      更新时间:2023-10-16

因此,对于我的项目,我需要制作一个包含指向4个不同方向的节点的链表。这是节点声明:

class Node {
public:
    Node(string newname);
    Node();
    void setNodeName(string newname);
    string getNodeName();
    void attachNewNode(Node *newNode, int direction);
    Node *getAttachedNode(int direction);
private:
    string name;
    Node *attachedNodes[4];
};

这是我的实现:

Node::Node(string newname) {
    newname = name;
    for (int i = 0; i < 3; i++) {
        attachedNodes[i] = NULL;
    }
}
Node::Node() {
    for (int i = 0; i < 3; i++) {
        attachedNodes[i] = NULL;
    }
}
void Node::setNodeName(string newname) {
    newname = name;
}
string Node::getNodeName() {
    return name;
}
void Node::attachNewNode(Node *newNode, int direction){
    newNode = attachedNodes[direction];
}
Node *getAttachedNode(int direction) {
    return attachedNodes[direction];
}

代码getAttachedNode(int direction)方法在返回行中给出错误:"使用未声明的标识符'attachedNodes'"。指针总是把我搞砸,我相信这就是问题所在。我也不确定我是否有用于函数实现的正确逻辑。有语法错误吗?还是我实施它们错了?我该如何解决这个问题?

就像这样:

Node* Node::getAttachedNode(int direction) {
    return attachedNodes[direction];
}

就像你的其他方法一样。