c ++从模板派生的类如何调用模板的构造函数? [英] c++ how does a class derived from a template call the template's constructor?

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

问题描述

我真的不知道如何调用这个线程。
情况如下。我有一个模板类 Array< T>

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);
}

现在,我想写一个从 Array< T> ,持有类框的对象

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) {}
};

我按照以下方式操作:

class BoxesArray : public Array<Boxes>{
public:
    BoxesArray() : Array<Boxes>::Array() {}
    BoxesArray(int nValue) : Array<Boxes>::Array(nValue) {}
}

我添加了一些额外的功能,仅仅用于 Boxes 。好吧,所以这里是混乱第一。调用 ArrayBoxes()似乎实例化一个对象Array和prep这个对象来保存盒子,对吧?但是它是如何发生的(即,上述代码的哪一部分),在创建和对象 ArrayBoxes 我已经填充了Boxes?第二个问题,我可以看到,这些填充ArrayBoxes的框是使用默认的框架构造函数构造的(框 m_dFull 被设置为0),但如果我会例如ArrayBoxes将被默认使用Boxes的参数构造函数(给定,例如Boxes m_dFull = 0.5 )实例化?

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.

推荐答案


但是怎么会发生,上述代码的哪一部分)在创建和对象ArrayBoxes后,我已经填充了Boxes?

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?

看起来您的 BoxesArray 构造函数调用 ; Boxes> 构造函数。即使没有,C ++也会为你隐式调用它。

It appears your BoxesArray constructor calls the Array<Boxes> constructor. Even if it didn't, C++ will implicitly call it for you.


第二个问题,我可以看到, fill ArrayBoxes是使用Boxes的默认构造函数构造的(Boxes m_dFull设置为0),但是如果我想使用Boxes的参数构造函数(例如Boxes m_dFull = 0.5)来默认实例化ArrayBox, p>

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)?

您需要在 Array< T> 中添加一个构造函数:
数组(int nsize,double defval);

You need to add a constructor like so in Array<T>: Array(int nsize, double defval);

默认值。

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

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