动态分配自定义类的数组和重载运算符

Dynamically allocating array of a custom class and overloading operators

本文关键字:重载 运算符 数组 自定义 动态分配      更新时间:2023-10-16

在过去的几天里,我一直在试图弄清楚如何为我制作的这个类制作一个动态分配的数组。其中一个包括我制作的另一个课程

以下是课程:

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[] 运算符,它完全没有做任何事情。

有人可以解释一下这样做的正确方法是什么吗?

数组中确实有多个对象,但t不是数组。

t是指向一个BST 的指针,调试器会这样显示它 – 调试器不知道它是指向数组第一个元素的指针。

如果要将其视为数组,则需要告诉调试器执行此操作。
您在"监视"窗口中执行此操作,我认为语法对于显示前两个元素t,2