抽象类的Std::shared_ptr来实例化派生类
std::shared_ptr of abstract class to instantiate derived class
我试图使用std::shared_ptr
,但我不确定是否可以使用shared_ptr
作为抽象类,并从这个智能指针调用派生类。这是我目前的代码
IExecute *ppCIExecuteExecuteOperation = NULL;
for(int i = 0; i < 3; ++i)
{
switch (stOperationType.key)
{
case E_OPERATIONKEY::DrawCircle:
pCIExecuteExecuteOperation = new CCircle();
break;
case E_OPERATIONKEY::DrawSquare:
pCIExecuteExecuteOperation = new CSquare();
break;
case E_OPERATIONKEY::Rhombus:
pCIExecuteExecuteOperation = new CRehombus();
break;
default:
break;
}
}
pCIExecuteExecuteOperation->Draw();
这里IExecute是一个抽象类,circle, CSquare, CRhombus是IExecute的派生类。
我想做的就是使用shared_ptr<IEXectue>pCIExecuteExecuteOperation(nullptr)
并且在switch语句中使其指向派生类之一,我如何实现这一点?
编辑:答案是使用make_shared或reset()
谢谢大家,我没想到这么简单。
这很简单。看看代码,感受一下。
std::shared_ptr<IExecute> ppCIExecuteExecuteOperation;
for(int i = 0; i < 3; ++i)
{
switch (stOperationType.key)
{
case E_OPERATIONKEY::DrawCircle:
pCIExecuteExecuteOperation.reset(new CCircle());
break;
case E_OPERATIONKEY::DrawSquare:
pCIExecuteExecuteOperation.reset(new CSquare());
break;
case E_OPERATIONKEY::Rhombus:
pCIExecuteExecuteOperation.reset(new CRehombus());
break;
default:
break;
}
}
pCIExecuteExecuteOperation->Draw();
IExecute *ppCIExecuteExecuteOperation = NULL;
应替换为
std::shared_ptr<IExecute> pExecute;
,然后每个赋值行都可以写成
pExecute.reset(new CCircle);
则可以调用Draw
pExecute->Draw();
方法std::make_shared<T>
创建一个类型为T
的共享指针对象,并调用其构造函数。所以不调用new
,调用std::make_shared
。
std::shared_ptr<IEXectue>pCIExecuteExecuteOperation(nullptr);
...
...
switch (stOperationType.key)
{
case E_OPERATIONKEY::DrawCircle:
pCIExecuteExecuteOperation = std::make_shared<CCircle>();
break;
...
std::make_shared
还可以使用参数,这些参数被转发给构造函数,前提是存在具有该参数列表的构造函数。
相关文章:
- 从模板基类派生是否在派生类声明的点实例化模板
- 派生模板类对象的实例化
- 为什么不能在实例化对基类的引用的同时实例化指向派生类的指针?
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 为什么C++可以使用派生结构来实例化其父模板结构,而父模板可以调用子结构的函数?
- 如何在不实例化派生类的情况下管理一组派生类枚举
- C++ 实例化派生类的语法异常
- 是否可以在不实例化派生类的情况下调用该类的虚拟函数
- Cython C 类继承无法实例化派生类
- 我做了什么?需要在模板化类的方法中实例化派生类
- C++ - 实例化派生类并使用基类的构造函数
- 如何通过映射实例化派生类中的对象
- 只实例化派生类一次错误的 OOP
- 实例化派生自接口的类,该接口位于派生自接口的另一个类中...只需阅读即可找出答案
- 实例化派生类对象,该对象的基类ctor是私有的
- 抽象类的Std::shared_ptr来实例化派生类
- 在c++中实例化派生类型
- 强制实例化派生类型而不是基类型
- 如何实例化派生类而不必重写代码
- C++-根据上下文实例化派生类