相关疑难解决方法(0)

如何使用std :: shared_ptr实现多态?

我已经看到了关于这个主题的一些其他问题,但仍然没有找到答案 - 我想我错过了一些东西:

我定义了两个简单的测试类:

class TestBase
{

  public:

    TestBase ( ) { };
    ~ TestBase ( ) { };

  protected:

    inline virtual int getInt ( )
    {
        return 0;
    }

};

class TestDerived : public TestBase
{

  protected:

    inline int getInt ( ) override
    {
        return 1;
    }

};
Run Code Online (Sandbox Code Playgroud)

我声明了typedef来简化它们的使用 std::shared_ptr:

typedef std::shared_ptr<TestBase> spBase;
typedef std::shared_ptr<TestDerived> spDerived;
Run Code Online (Sandbox Code Playgroud)

问题:我无法编译代码以shared_ptr多态方式使用这些声明,即使base在所有这些情况下实际上是一个实例spDerived:

spBase base;
spDerived derived = static_cast < spDerived > ( base );
Run Code Online (Sandbox Code Playgroud)

错误:没有匹配函数来调用'std :: shared_ptr :: …

polymorphism gcc casting shared-ptr c++11

15
推荐指数
1
解决办法
8838
查看次数

标签 统计

c++11 ×1

casting ×1

gcc ×1

polymorphism ×1

shared-ptr ×1