首页 > 解决方案 > 将对象的副本添加到对象指针数组

问题描述

我正在尝试将节点类的对象的副本添加到存储在另一个名为 nodelist 类的类中的对象数组中。

public:
  
    Node(int row, int col, int dist_traveled);
    ~Node();
    Node(Node &other);

private:
    int row;
    int col;
    int dist_traveled;  // distance from start node
};
Node::Node(int row, int col, int dist_traveled):
    row(row), col(col), dist_traveled(dist_traveled)
{}
Node:: Node(Node &other):
    row(other.row), col(other.col), dist_traveled(other.dist_traveled)
{}

Node::~Node(){}                

并且包含添加上述Node类对象的函数的nodelist类包含

class NodeList{
public:
    NodeList();
    ~NodeList();
    NodeList(NodeList& other);
    // Number of elements in the NodeList
    int getLength();
    // Add a COPY node element to the BACK of the nodelist.
    void addElement(Node* newNode);
    // Get a pointer to the ith node in the node list
    Node* getNode(int i);
private:
    Node* nodes[NODE_LIST_ARRAY_MAX_SIZE];
    // Number of nodes currently in the NodeList
    int length;
};
NodeList::NodeList():
    length(0)
{
    for (int i = 0; i<NODE_LIST_ARRAY_MAX_SIZE; i++)
    {
        nodes[i] = nullptr;
    }
}

NodeList::~NodeList()
{
    for (int i = 0; i<NODE_LIST_ARRAY_MAX_SIZE; i++)
    {
        if(nodes[i]!=nullptr)
        {
            delete nodes[i];
        }
    }
}

NodeList::NodeList(NodeList& other){
    for (int i = 0; i<NODE_LIST_ARRAY_MAX_SIZE; i++)
    {
        nodes[i] = new Node(*other.nodes[i]);
    }
}

int NodeList::getLength(){
    return length;
}

void NodeList::addElement(Node* newPos){
    Node* copy = new Node(*newPos);
    nodes[length] = copy;
    length++;
}

Node* NodeList::getNode(int i){
    return nodes[i];
}

当我的程序调用 nodeList 类中的 addElement 函数时出现分段错误,我似乎无法弄清楚原因。谁能帮帮我?

对不起,如果代码太长只是想确保我的问题很清楚

标签: c++arraysclassobjectpointers

解决方案


推荐阅读