std :: shared_ptr和继承

时间:2014-07-07 05:00:31

标签: c++ inheritance c++11 boost shared-ptr

我在shared_ptr继承类之间进行自动类型转换时遇到了一些问题。

我的类结构如下,基类Base和两个派生类Derived1Derived2

// Base class
class Base {
protected:
  ...
  ...
public:
  Base() = default;
  virtual ~Base() = default;
  virtual void run() = 0;
  ...
  ...
};

// Derived class
class Derived1: Base {
protected:
  ...
  ...
public:
  Derived1() = default;
  virtual ~Derived1() = default;
  void run() {...}
  ...
  ...
};

// Derived class
class Derived2: Base {
protected:
  ...
  ...
public:
  Derived2() = default;
  virtual ~Derived2() = default;
  void run() {...}
  ...
  ...
};

我有一个函数doSomething()

void doSomething(std::shared_ptr<Base> ptr) {
  ptr->run();
  ...
}

我用派生类调用函数,如此 -

doSomething(make_shared<Derived1>())
doSomething(make_shared<Derived2>())

但我收到错误说 -

no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>'
no viable conversion from 'shared_ptr<class Derived1>' to 'shared_ptr<class Base>'

我做错了什么?将static_pointer_cast用于Base类型是否安全?喜欢 -

doSomething(static_pointer_cast<Base>(make_sahred<Derived2>()))

的 我的坏......问题是我私下继承了基类。

1 个答案:

答案 0 :(得分:7)

据我所知,您提供的代码编译得很好:http://ideone.com/06RB2W

#include <memory>

class Base {
    public:
        Base() = default;
        virtual ~Base() = default;
        virtual void run() = 0;
};

class Derived1: public Base {
    public:
        Derived1() = default;
        virtual ~Derived1() = default;
        void run() {}
};

class Derived2: public Base {
    public:
        Derived2() = default;
        virtual ~Derived2() = default;
        void run() {}
};

void doSomething(std::shared_ptr<Base> ptr) {
    ptr->run();
}

int main() {
    doSomething(std::make_shared<Derived1>());
    doSomething(std::make_shared<Derived2>());
}