通用继承和复制构造函数

时间:2015-07-09 08:10:37

标签: c++ generics inheritance constructor copy

我创建了一个通用的Array类,然后使用泛型继承来创建一个NumericArray类。当我使用默认的复制构造函数(在NumericArray中)时,我从我的成员函数中得到了正确的结果;但是,当我在NumericArray类中实现自己的复制构造函数时,我得到的结果不正确。特别是,NumericArray.h中的自由函数依赖于NumericArray复制构造函数,会产生奇怪的值,例如-8386226262。

通用数组的复制构造函数是:

template <typename Type>
Array<Type>::Array(const Array<Type>& data) // copy constructor 
{
    m_size = data.m_size; // set m_size to the size of the data which should be copied
    m_data = new Type[m_size]; // allocate memory on the heap for m_data to be copied from the new data array 
    for (int i = 0; i < m_size; ++i)
    {
        m_data[i] = data.m_data[i]; // copy each element one at a time 
    }
    cout << "Copy called" << endl;
}

和一般继承的NumericArray的复制构造函数是:

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source)
{
    Array<Type>::Array(source); // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
    cout << "Numeric copy called!" << endl;
}

您注意到这些实施有什么问题吗?

对于任何想要完全访问该程序的人,我把它放在Dropbox上,在这里: https://www.dropbox.com/sh/86c5o702vkjyrwx/AAB-Pnpl_jPR_GT4qiPYb8LTa?dl=0

1 个答案:

答案 0 :(得分:1)

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source)
{
    Array<Type>::Array(source); // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
    cout << "Numeric copy called!" << endl;
}

应该是

template <typename Type> // copy constructor 
NumericArray<Type>::NumericArray(const NumericArray<Type> &source) :
    Array<Type>::Array(source) // calls the copy constructor of a generic Array (since a numeric array performs the same copy as a generic array here)
{
    cout << "Numeric copy called!" << endl;
}

因为以下内容属于您的功能

Array<Type>::Array(source);
相关问题