问题
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