错误C2259:“派生”无法实例化抽象类

时间:2013-10-24 10:39:14

标签: c++ boost-python pure-virtual

如何通过使用boost python调用派生类中的纯虚函数。我得到的错误是无法实例化抽象基类。示例代码如下:

class Base
{
public: 
    virtual int test() = 0;
};

class Derived : public Base
{
public:
    int  test()
    {
        int  a = 10;
        return a;
    }
};

struct  BaseWrap : Base, wrapper<Base>
{
    Int  test() 
    {
        return this->get_override(“test”)();
    }
};

BOOST_PYTHON_MODULE(Pure_Virtual) 
{
    Class_<BaseWrap, boost::noncopyable>(“Base”, no_init)
    .def(“test”, pure_virtual($Base::test)
    ;

    Class_<Derived, bases<Base> >(“Derived”)
    .def(“test”, &Derived::test)
    ;   
}

1 个答案:

答案 0 :(得分:1)

纯虚函数的调用方式与非纯虚函数相同。唯一的区别是,作为纯虚拟Python方法公开的函数在调用时会引发RuntimeError

初始发布的代码存在各种语法问题,因此很难确切地确定问题所在。但是,这是一个基于原始代码的完整示例:

#include <boost/python.hpp>

namespace python = boost::python;

class Base
{
public:
  virtual int test() = 0;
  virtual ~Base() {}
};

class Derived
  : public Base
{
public:
  int test() { return 10; }
};

struct BaseWrap
  : Base, python::wrapper<Base>
{
  int test() 
  {
    return this->get_override("test")();
  }
};

BOOST_PYTHON_MODULE(example) 
{
  python::class_<BaseWrap, boost::noncopyable>("Base")
    .def("test", python::pure_virtual(&BaseWrap::test))
    ;

  python::class_<Derived, python::bases<Base> >("Derived")
    .def("test", &Derived::test)
    ;   
}

及其用法:

>>> import example
>>> derived = example.Derived()
>>> derived.test()
10
>>> class Spam(example.Base):
...     pass
... 
>>> s = Spam()
>>> s.test()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Pure virtual function called
>>> class Egg(example.Base):
...     def test(self):
...         return 42
... 
>>> e = Egg()
>>> e.test()
42

在从test()继承但未实现example.Base方法的类型上调用test()时,Boost.Python将引发RuntimeError,表示纯虚函数已被调用。因此,test()对象上的Spam会引发异常,其中test()对象上的Egg已正确分派。