我有一个简单的 C++ Node 类,它包含指向同一类型的指针的数组数据成员。这个数组是动态分配的,它的指针应该默认为 null 但我不确定如何实现它。
class Node
{
private:
Node *_nextNode[];
string _data;
}
Node::Node( const string &p_data, const int &p_levels ): _data(p_data)
{
//unsure how to initialize the '_nextNode[]' member so that the size of the array is of p_levels and they all default to null pointers
}
class SkipList
{
private:
}
最佳答案
使用 std::vector<Node*>
:
Node::Node( const string &p_data, const int &p_levels ):
_data(p_data),
_nextNode(p_levels)
{
这将初始化 _nextNode
的元素至 nullptr
考虑使用 smart pointer implementation而不是 Node*
管理 Node
的销毁实例给你。
如果你必须使用 Node*
那么你需要一个Node**
指向 Node*
的列表:
class Node
{
private:
Node**_nextNode;
string _data;
};
Node::Node( const string &p_data, const int &p_levels ):
_data(p_data),
_nextNode(new Node*[p_levels]())
{ //^^ value initialization.
分配 int*
的数组包含 p_levels
元素和值初始化它们(将它们设置为 NULL
)。 Node
需要知道 _nextNode
中存储了多少元素所以p_levels
还需要存储。销毁:
for (int i = 0; i < _nextNodeElements; i++)
{
delete _nextNode[i]; // delete NULL is safe, a no-op.
}
delete[] _nextNode;
只为将你推向std::vector
再次:std::vector<std::unique_ptr<Node>> _nextNode;
不需要手写的析构函数,默认生成的析构函数就足够了。
关于c++ - 将对象指针的数据成员数组初始化为正确的大小和 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16378612/