【发布时间】:2014-10-13 19:54:41
【问题描述】:
我正在尝试使用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是一个抽象类,CCircle、CSquare、CRhombus是IExecute的派生类。
我只想使用shared_ptr<IEXectue>pCIExecuteExecuteOperation(nullptr)
并在 switch 语句中使其指向派生类之一,我该如何实现?
编辑: 答案是使用 make_shared 或 reset()
谢谢大家,我没想到会这么简单。
【问题讨论】:
-
你真的尝试过吗?
-
显而易见的方法应该可行。
-
@Geoffroy:我是 c++ shared_ptr 的新手,浏览了几个站点并且很困惑
标签: c++ inheritance c++11 smart-pointers