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

左心房为你撑大大i 提交于 2020-01-25 12:47:48

问题


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.



来源:https://stackoverflow.com/questions/15437784/c-how-does-a-class-derived-from-a-template-call-the-templates-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!