我们可以在C ++中使类构造函数虚拟化以创建多态对象吗?不会。C++是静态类型的(RTTI的目的有所不同)语言,对于C ++编译器来说,多态创建对象是没有意义的。编译器必须知道创建对象的类类型。换句话说,从C ++编译器的角度来看,要创建哪种类型的对象是编译时的决定。如果我们将构造函数设为虚拟,则编译器会标记错误。实际上,除了inline之外,构造函数的声明中不允许其他关键字。
在实际情况下,我们需要基于一些输入在类层次结构中创建派生类对象。换句话说,对象创建和对象类型紧密耦合,这迫使修改扩展。虚拟构造器的目的是使对象创建与类型脱钩。
我们如何在运行时创建所需的对象类型?例如,请参见下面的示例程序。
#include <iostream>
using namespace std;
LIBRARY START
class Base
{
public:
Base() { }
virtual // Ensures to invoke actual object destructor
~Base() { }
// An interface
virtual void DisplayAction() = 0;
};
class Derived1 : public Base
{
public:
Derived1()
{
cout << "Derived1 created" << endl;
}
~Derived1()
{
cout << "Derived1 destroyed" << endl;
}
void DisplayAction()
{
cout << "Action from Derived1" << endl;
}
};
class Derived2 : public Base
{
public:
Derived2()
{
cout << "Derived2 created" << endl;
}
~Derived2()
{
cout << "Derived2 destroyed" << endl;
}
void DisplayAction()
{
cout << "Action from Derived2" << endl;
}
};
LIBRARY END
class User
{
public:
// Creates Drived1
User() : pBase(nullptr)
{
// What if Derived2 is required? - Add an if-else ladder (see next sample)
pBase = new Derived1();
}
~User()
{
if( pBase )
{
delete pBase;
pBase = nullptr;
}
}
// Delegates to actual object
void Action()
{
pBase->DisplayAction();
}
private:
Base *pBase;
};
int