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

时间:2014-08-20 12:42:42

标签: c++ inheritance c++11 smart-pointers

我正在尝试使用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()

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

3 个答案:

答案 0 :(得分:5)

这很容易。看看代码和感受。

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();

答案 1 :(得分:2)

方法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也能够使用转发器,转发给构造函数,假设有一个带有该参数列表的构造函数。

答案 2 :(得分:1)

该行

IExecute *ppCIExecuteExecuteOperation = NULL;

应替换为

std::shared_ptr<IExecute> pExecute;

然后每个带有赋值的行都可以写成

pExecute.reset(new CCircle);

然后你可以拨打Draw

pExecute->Draw();
相关问题