双指针对象数组-克隆元素
Double pointers Array of objects - Clone Elements
我试图掌握继承和深度复制的窍门,但遇到了一些麻烦。我有三个类别(1个基础和2个衍生)如下:
class Base {
protected:
int id;
public:
Base(int i) : id(i) {};
virtual ~Base();
};
class DeriveA : public Base {
int specialID;
public:
DeriveA(int s, int i) : Base(i), specialID(s) {};
~DeriveA();
};
class DeriveB : public Base {
int specialID;
public:
DeriveB(int s, int i) : Base(i), specialID(s) {};
~DeriveB();
};
在我的主页上,我有这样的东西:
int main() {
Base **Array;
int i, n;
Array = new Base*[5];
for (i = 0 ; i < 5 ; i++) {
n = rand() % 2;
if (n)
Array[i] = new DeriveA(i, n);
else
Array[i] = new DeriveB(i, n);
}
}
如果满足特定情况,我想将阵列对象硬拷贝到其他对象上。我发现很难为它创建一个复制构造函数,因为Array[0] = Array[2];
对我不起作用。我不想使用任何向量或std::copy,因为这不是我的"教育"目标。
PS1:由于我已经初始化了数组的所有对象,赋值运算符是否更好地用于此目的。
PS 2:由于这是一个通用代码,所以我遗漏了一些错误。请忽略它们,专注于问题。
首先,您应该已经分配了Base*
:的数组
Array = new Base*[5];
这就是初始化元素指针的方式:
Array[i] = new DeriveA(i,n);
不是这样的:
// * added for further clarification, otherwise invalid and rejected at compilation
*Array[i] = DeriveA(i,n);
因为那就是:
- 取消引用未初始化的指针(未定义的行为)
- 对象切片
请注意,您的Base
缺少一个virtual
析构函数。
然后当然是交易。。。你可以在这里找到怎么做。
如果您想克隆对象,而不是复制指向同一对象的指针,您可以使用虚拟克隆功能:
class Base {
public:
virtual Base* clone() const = 0;
virtual ~Base(); // Don't forget 'virtual' here
};
class DeriveA : public Base {
public:
virtual Base* clone() const { return new DeriveA(*this); }
};
class DeriveB : public Base {
public:
virtual Base* clone() const { return new DeriveB(*this); }
};
// ...
Array[0] = Array[2]->clone();
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 提升灵气:省略克莱恩星辰解析器中的元素