【发布时间】:2018-01-04 02:11:40
【问题描述】:
最近几天我一直在试图弄清楚如何为我制作的这个类创建一个动态分配的数组。其中一个包括我制作的另一个类
以下是课程:
template<typename T>
class BST // a binary search tree class
{
private:
Node<T> * root;
int size;
public:
BST()
{
root = NULL;
size = 0;
}
/*void * BST::operator new[](size_t a) //tried it both with the "BST::" and without
{
void * p = malloc(a);//24
return p;
}*/
//there are more functions that i cut out
}
和
template <typename T>
class Node //a node for a binary search tree
{
public:
int key;
T data;
Node * left;
Node * right;
Node * parent;
//public:
Node<T>()
{
key = NULL;
data = NULL;
left = NULL;
right = NULL;
parent = NULL;
}
//more stuff below this but it's just getting and setting the data
}
在main() 中,我将尝试使用这一行创建一个BST 对象数组:
BST<char> * t = new BST<char>[ n ]; //the user will give the value for int n
问题是它在运行时只生成一个BST 对象。我已经做了一些研究并尝试重载 new[] 运算符,但它什么也没做。
谁能解释一下正确的方法是什么?
【问题讨论】:
-
您想在开始时分配所有节点,还是想在向树中添加新项目时动态增长树?此外,您应该在 Node 的构造函数中使用初始化语法,因为在当前设计中,您将 T 限制为可以分配给 NULL 的类型。
-
"问题是它在运行时只生成一个 BST 对象" 它生成
n对象。你是说n == 1? -
@juanchopanza 我将 n 设置为 3,它只会生成一个对象。
-
@ChrisDouglas 不太可能,除非代码在一个对象后崩溃。 minimal reproducible example 或者它没有发生。
-
@Rudi 当我第一次创建 BST 对象时,根节点应该为空,之后可以插入对象。不过,分配 Node 对象不会造成任何问题。就在我尝试制作 BST 对象数组时 :)
标签: c++ arrays operator-overloading dynamic-memory-allocation