C/C++编程笔记:高级C++知识 | 虚拟构造器

我们可以在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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值