简体   繁体   中英

c++ how does a class derived from a template call the template's constructor?

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 (ie, 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.

您需要在默认构造函数的主体中放入代码以使用满足您要求的Boxes填充数组,或者调用Array<Boxes>的非默认构造函数,该构造函数将您想要在成员初始化中使用的Boxes实例清单。

But how does it happen (ie, 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.

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