c++ how does a class derived from a template call

2019-09-06 17:15发布

问题:

I didn't really know how to call this thread. The situation is the following. I have a template class Array<T>:

template <typename T> class Array{
private:
    T* m_cData;
    int m_nSize;
    static int s_iDefualtSize;
public:
    Array();
    Array(int nSize);
}

Now, I would like to write a specialized class derived from Array<T>, holding objects of class Boxes:

class Boxes{
private:
    double m_dFull;
public:
    Boxes(double dFull=0): m_dFull(dFull) {}
};

I do that in the following manner:

class BoxesArray : public Array<Boxes>{
public:
    BoxesArray() : Array<Boxes>::Array() {}
    BoxesArray(int nValue) : Array<Boxes>::Array(nValue) {}
}

and I add some extra functionality meant solely for Boxes. Ok, so here comes confusion number one. Calling ArrayBoxes() seem to instantiate an object Array and "prep" this object to hold Boxes, right? But how does it happen (i.e., which part of the above code) that after creating and object ArrayBoxes I have it filled already with Boxes? And, the second question, I can see that these Boxes that fill ArrayBoxes are constructed using the default constructor of Boxes (Boxes m_dFull is being set to 0) but what if I would like the ArrayBoxes to be instantiated by default using parametric constructor of Boxes (giving, say, Boxes m_dFull = 0.5)? Hope with all the edits my question is clear now.

回答1:

You'll need to put the code to populate the array with Boxes fulfilling your requirements in the body of your default constructor, or call a non-default constructor of Array<Boxes> that takes the Boxes instances you want to have in the member initialization list.



回答2:

But how does it happen (i.e., which part of the above code) that after creating and object ArrayBoxes I have it filled already with Boxes?

It appears your BoxesArray constructor calls the Array<Boxes> constructor. Even if it didn't, C++ will implicitly call it for you.

And, the second question, I can see that these Boxes that fill ArrayBoxes are constructed using the default constructor of Boxes (Boxes m_dFull is being set to 0) but what if I would like the ArrayBoxes to be instantiated by default using parametric constructor of Boxes (giving, say, Boxes m_dFull = 0.5)?

You need to add a constructor like so in Array<T>: Array(int nsize, double defval);

Inside you will construct the array with the boxes calling the default value.