问题
I have the following template class:
template<typename T, int nSize> class Stack{
private:
int m_nCurrentPos;
Array<T> m_tArray;
public:
Stack(int nCurrentPos = 0);
...
};
I would like the default constructor work as follows:
template<typename T, int nSize> Stack<T,nSize>::Stack(int nCurrent){
m_nCurrent = nCurrentPos;
m_tArray = Array<T>::Array(nSize);
};
Where Array looks like that:
template <typename T> class Array{
private:
T* m_cData;
int m_nSize;
static int s_nDefaultSize;
public:
Array();
Array(int nSize);
...
};
And its constructors are:
template<typename T> Array<T>::Array(){
m_nSize = s_nDefaultSize;
m_cData = new T[m_nSize];
}
and, obviously,
template<typename T> Array<T>::Array(int nSize){
m_nSize = nSize;
m_cData = new T[m_nSize];
}
So, Stack is composed from Array and some extra functionalities. My problem is that when in Array I define s_nDefaultSize
to be say 512
, and I try to instantiate Stack<int,1024>
I'm getting an exception from class Array, saying that I'm trying to assign two arrays of different length. As soon as I change the code such that s_nDefaultSize=1024
(so it matches the template's non-type argument nSize
), everything's fine. So, in other words, the exception occurs as soon as s_nDefaultSize != nSize
. So, my guess is that in the code above, in the default constructor of Stack<T,nSize>
, i.e., m_tArray = Array<T>::Array(nSize);
the m_tArray
is created by default constructor of Array (employing s_nDefaultSize
) and only then the compiler tries to assign it to Array<T>::Array(nSize)
(employing my nSize
value). Is that correct? And if yes, how can I change this behaviour? This is another question that I posted yesterday, which, even though is about inheritance, not composition, is very much related to the question in this thread. Cheers!
回答1:
You need to use a member initialization list with the constructor of Stack
:
template<typename T, int nSize>
Stack<T,nSize>::Stack(int nCurrent)
: m_tArray(nSize)
{
m_nCurrent = nCurrentPos;
};
As you have it, m_tArray
will first be default constructed and then assigned to in your constructor. Here, we use the member initialization list to initialize m_tArray
to the right size immediately.
来源:https://stackoverflow.com/questions/15451335/c-is-default-constructor-called-in-parametrized-constructor