<分区>
我正在尝试使用 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()
谢谢大家,我没想到会这么简单。