c++ - 将对象的副本添加到对象指针数组
问题描述
我正在尝试将节点类的对象的副本添加到存储在另一个名为 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 函数时出现分段错误,我似乎无法弄清楚原因。谁能帮帮我?
对不起,如果代码太长只是想确保我的问题很清楚
解决方案
推荐阅读
- python - Graph 执行中不允许使用 `tf.Tensor` 作为 Python `bool`。使用 Eager 执行或用 @tf.function 修饰这个函数
- django - DRF 所需的搜索过滤器
- html - 图像的最大宽度在 IE 11 的 flexbox 中不起作用,但适用于谷歌浏览器
- javascript - 我无法在 if 语句中分配变量
- r - 将 ggplot 中的 x 轴设置为在最后一个日期数据结束时可用于
- django - 'list' 对象没有属性 'json'
- php - Laravel 无需事先排序即可获取最新行
- python - 跨解释器理解 Python `id` 函数
- javascript - Redux 和 Axios 得到。方法不返回任何数据
- python - 如何在 Windows 上的 Vim(不是 gVim)中获得 Python 支持