How to call constructor of a template base class in a template derived class?

亡梦爱人 提交于 2021-02-06 09:04:29

问题


Let's say I have a base template class Array:

template <class T = Point> class Array{
    protected:
        T* m_data;
        int size;
    public:
        Array();    // constructor
        Array(int n);   // constructor
        Array(const Array<T>& s_data);  //Copy Constructor
        // and so on..
}

And it has constructors and destructors. Also I have a derived template class NumericArray:

template <class T = int> 
class NumericArray:public Array<T>{

    public:
        NumericArray();
        NumericArray(int n);
        NumericArray(const NumericArray<T>& s_data);

        ~NumericArray();    //destructor

};

Since I need to initialize the private members in the base class so I need to call the base constructors in the derived constructors. But how? I tried

template <class T>
NumericArray<T>::NumericArray(int n){
    Array<T>(n);  // it will think I create a Array<T> names n
}

template <class T>
NumericArray<T>::NumericArray(int n):Array(n){
    // No field in NumericalArray called Array
}

Any idea?


回答1:


Combine your solutions, use the initializer list and the full name:

NumericArray<T>::NumericArray(int n)
 : Array<T>(n)
{

}

Also, since they become a dependent name, fields of Array have to be accessed like this:

Array<T>::m_data; // inside a NumericArray method

Also, if it's not some experiment or homework, please use std::vector instead of pointer and size.



来源:https://stackoverflow.com/questions/25064515/how-to-call-constructor-of-a-template-base-class-in-a-template-derived-class

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