std :: shared_ptr的抽象类来实例化派生类

Bar*_*rry 2 c++ inheritance smart-pointers c++11

我正在尝试使用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();
Run Code Online (Sandbox Code Playgroud)

这里IExecute是一个抽象类,CCircle,CSquare,CRhombus是IExecute的派生类.

我想要做的就是使用shared_ptr<IEXectue>pCIExecuteExecuteOperation(nullptr) 并在switch语句中使其指向派生类之一,我该如何实现?

编辑:答案是使用make_shared或reset()

谢谢大家,我希望它很容易.

ikh*_*ikh 6

这很简单.看看代码和感觉.

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();
Run Code Online (Sandbox Code Playgroud)