双指针对象数组-克隆元素

Double pointers Array of objects - Clone Elements

本文关键字:元素 -克 数组 指针 对象      更新时间:2023-10-16

我试图掌握继承和深度复制的窍门,但遇到了一些麻烦。我有三个类别(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);

因为那就是:

  1. 取消引用未初始化的指针(未定义的行为)
  2. 对象切片

请注意,您的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();