我可以用这个技巧破坏基类并在派生中重新创建它吗?
class base: noncopyable
{
base(); //ctor with none param
base(int x); //ctor with one param
base(int x, int y); //ctor with two param
virtual ~base();
}
struct params
{
int x;
int y;
enum
{
typeNoneParam, //neither x nor y is defined
typeOneParam, //only x is defined
typeTwoParam //x and y both are defined
}typeParam;
}
class Derived
{
Derived(params p); //construct base class conditionally by p.typeParam
}
Derived::Derived(params p)
:base() //default typeNoneParam
{
//typeNoneParam need not do special process
if (p.typeParam == params::typeOneParam)
{
base::~base(); //delete the default-typeNoneParam creation by base-dtor
base(p.x); //recreate the new base with one-param base-ctor
}
if (p.typeParam == params::typeOneParam)
{
base::~base(); //delete the default-typeNoneParam creation by base-dtor
base(p.x, p.y); //recreate the new base with two-param base-ctor
}
}
类派生和基类的所有声明都不能改变,结构参数也不能改变。
只有派生类的实现是允许更改的。
任何人都可以给出关于实施正确的想法吗?任何其他更温和的实现都可以很好地满足这种情况(使用动态选择 base-ctor 初始化不可复制的基类)?