我有几个孩子班都有相同的父母。每个子类都可以使用包含在父对象中的一些数据来构造。我想使用基础对象中包含的信息将一个孩子变成另一个孩子(不修改基础对象)。
目前它的实现如下例所示:
#include <iostream>
using namespace std;
class Data {};
class base
{
public:
base() {}
base(Data input) : data(input) {}
virtual ~base() { cout << "Deleting :" << this->name() << endl; }
template<class T> static base* CastToDerrived(base* object)
{
T* output = new T(object->data);
delete object;
return output;
}
virtual const char* name() {return "base";}
Data data;
};
class derrived1 : public base
{
public:
derrived1() {}
derrived1(Data input): base(input){}
~derrived1(){cout << "Deleting :" << this->name() << endl;}
const char* name(){return "derrived1";}
};
class derrived2 : public base
{
public:
derrived2(){}
derrived2(Data input): base(input){}
~derrived2(){cout << "Deleting :\t" << this->name() << endl;}
const char* name(){return "derrived2";}
};
int main(int argc, char *argv[])
{
base* object = new derrived1();
cout << "Created :\t"<<object->name()<<endl;
object = base::CastToDerrived<derrived2>(object);
cout << "Casted to :\t"<<object->name()<<endl;
}
哪个输出:
Created : derrived1
Deleting :derrived1
Deleting :base
Casted to : derrived2
但是,这需要销毁并再次创建基类,我想避免这种情况 - 我想销毁 derrived1,使用 base 构造 derrived2,但保持基类完整。最好的方法是什么?
(有几个派生类,基类为所有提供了通用接口,一些派生类以后会在不修改基类的情况下添加)。