我试图摆脱继承和深度复制的束缚,但遇到了一些麻烦。我有3个类(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,因为那不是我的“教育”目标。
PS 1:因为我已经初始化了数组的所有对象,所以赋值运算符更好地用于此目的。
PS 2:由于这是通用代码,因此我遗漏了一些错误。请忽略它们,并专注于问题。
如果要克隆对象,而不是将指针复制到同一对象,则可以使用虚拟克隆功能:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句