泛型继承和复制构造函数
Generic Inheritance and Copy Constructor
我创建了一个泛型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);
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类