【问题标题】:Dynamically allocating array of a custom class and overloading operators动态分配自定义类的数组并重载运算符
【发布时间】: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


【解决方案1】:

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

t 是一个指向 one BST 的指针,调试器将其显示为 - 调试器不知道它是指向数组第一个元素的指针。

如果您想将其视为一个数组,则需要告诉调试器这样做。
您在“观看”窗口中执行此操作,我认为语法将是 t,2 用于显示前两个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多