泛型继承和复制构造函数

Generic Inheritance and Copy Constructor

本文关键字:构造函数 复制 继承 泛型      更新时间:2023-10-16

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

泛型Array的复制构造函数为:

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

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