boost :: smart_ptr可以用于多态吗?

时间:2011-01-21 21:06:42

标签: c++ boost boost-smart-ptr

可以在多态中使用boost::smart_ptr例如scoped_ptr和shared_ptr吗?

class SomeClass
{
public:
    SomeClass()
    {
        a_ptr.reset(new SubClass);
    }
private:
    boost::scoped_ptr<SuperClass> a_ptr;
}

2 个答案:

答案 0 :(得分:6)

我相信答案是肯定的;对boost指针进行编码,以便在超类所在的任何地方都可以接受派生类。

答案 1 :(得分:4)

是:

#include <string>
#include <iostream>
using namespace std;
#include <boost\shared_ptr.hpp>
using namespace boost;


class Foo
{
public:
    virtual string speak() const { return "Foo"; }
    virtual ~Foo() {};
};

class Bar : public Foo
{
public:
    string speak() const { return "Bar"; }
};

int main()
{
    boost::shared_ptr<Foo> my_foo(new Bar);
    cout << my_foo->speak();
}

输出为:Bar