在C++面向对象程序设计中,我们都知道析构函数是可以虚拟的,但构造函数确是不能够虚拟的。原因在于虚拟调用是一种能够在给定信息不完全的情况下工作的机制。特别地,虚拟允许我们调用某个函数,对于这个函数,仅仅知道它的接口,而不知道具体的对 象类型。但是要建立一个对象,你必须拥有完全的信息。特别地,你需要知道要建立的对象的具体类型。因此,对构造函数的调用不可能是虚拟的。
但我们可以模拟虚拟构造函数。
这样的设计方案也许会对我们的程序设计有所帮助
但我们可以模拟虚拟构造函数。
class
Base
{
public:
Base(string key):m_key(key){}
string GetKey(){
return m_key;
}
virtual int GetValue()=0;
private:
string m_key;
} ;
class A: public Base
{
public:
A(string key):Base(key){}
int GetValue(){
return 1;
}
} ;
class B: public Base
{
public:
B(string key):Base(key){}
int GetValue(){
return 2;
}
} ;
class C: public Base
{
public:
C(string key):Base(key){}
int GetValue(){
return 3;
}
} ;
class Wrap
{
public:
Wrap(string key){
if(key=="a") m_obj= new A(key);
if(key=="b") m_obj= new B(key);
if(key=="c") m_obj=new C(key);
}
~Wrap(){
delete m_obj;
}
Base *GetObj(){
return m_obj;
}
private:
Base *m_obj;
} ;
{
public:
Base(string key):m_key(key){}
string GetKey(){
return m_key;
}
virtual int GetValue()=0;
private:
string m_key;
} ;
class A: public Base
{
public:
A(string key):Base(key){}
int GetValue(){
return 1;
}
} ;
class B: public Base
{
public:
B(string key):Base(key){}
int GetValue(){
return 2;
}
} ;
class C: public Base
{
public:
C(string key):Base(key){}
int GetValue(){
return 3;
}
} ;
class Wrap
{
public:
Wrap(string key){
if(key=="a") m_obj= new A(key);
if(key=="b") m_obj= new B(key);
if(key=="c") m_obj=new C(key);
}
~Wrap(){
delete m_obj;
}
Base *GetObj(){
return m_obj;
}
private:
Base *m_obj;
} ;
这样的设计方案也许会对我们的程序设计有所帮助