简体   繁体   中英

Constructor of a class within a template class

Created a generic tree, trying to use it with a custom class which holds a int value and an int array.

After trying to initialize the array in few different ways, none seem to go through to the main function. constructor of node class:

class ArrNode
{
    int id;
    int* arr;
    int length;
    public:
    ArrNode(int a, int b)
   {
       id = a;
       length = b;
       arr = new int[length]();
   }
    ~ArrNode()
    {
        if(arr != nullptr)
            delete arr;
    }
    int getArrVal(int i) const
    {
        return this->arr[i];
    }
};

template class:

template <class T>
class AvlTree
{
    private:
    T val;
    AvlTree *left;
    AvlTree *right;
    int height;
    public:
    AvlTree(ArrNode t) : val(t) {}
    T getVal()
    {
        return this->val;
    }

main function:

ArrNode t(5,3) //random numbers
AvlTree<ArrNode> a(t);

Assume there are working get functions for both the classes, i've tried:

  1. using a init list
  2. send a built up node into the the tree (the one pasted here)
  3. send int values and building up the node inside the tree constructor

all which worked in the scope of the function, but after returning to the main function the array was not initialized to zeroes as expected.

Note - trying not to use any of the std containers

So after further testing and help here, the mistake was doing not following the rule of 3, after implementing the copy assignment operator it worked as intended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM