可能是我在文档中遗漏了某些内容(或者只是无法进行正确的谷歌搜索),但我在使用shared_ptr和纯虚函数时遇到了问题。
下面是一个简短的可以工作的示例:
显然,这并不起作用,clang和其他编译器会抱怨: 在
下面是一个简短的可以工作的示例:
class Base
{
public:
virtual int stuff() = 0;
};
class Derived : public Base
{
public:
virtual int stuff() {return 6;}
};
class Container
{
public:
Container() : m_x( 0 ) {}
Container(Base* x) : m_x(x) {}
private:
Base* m_x;
};
因为我想使用新的高级 std::shared_ptr
,所以我修改了Container
如下:
class Container
{
public:
Container() : m_x( std::make_shared<Base>() ) {}
Container(const std::shared_ptr<Base>& x) : m_x(x) {}
private:
std::shared_ptr<Base> m_x;
};
显然,这并不起作用,clang和其他编译器会抱怨: 在
Container() : m_x( std::make_shared<Base>() ) {}
行中,error: allocating an object of abstract class type 'Base'
。所以问题来了:如何使用std :: shared_ptr
使其工作?
shared_ptr
不是必需的。 - dyp