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



我试图使用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还可以使用参数,这些参数被转发给构造函数,前提是存在具有该参数列表的构造函数。

最新更新