如何在模板派生类中调用模板基类的构造函数? [英] How to call constructor of a template base class in a template derived class?

查看:69
本文介绍了如何在模板派生类中调用模板基类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基础模板类Array:

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..
}

它具有构造函数和析构函数.我还有一个派生的模板类NumericArray:

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
}

有什么主意吗?

推荐答案

合并您的解决方案,使用初始化程序列表和全名:

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

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

}

此外,由于它们成为从属名称,因此必须像这样访问Array的字段:

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

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

此外,如果不是实验或家庭作业,请使用std :: vector而不是指针和大小.

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

这篇关于如何在模板派生类中调用模板基类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆