2

如何使用 boost python 将纯虚函数用于多重继承。我得到的错误是“Derived1”不能实例化抽象类。并且“Derived2”无法实例化抽象类。如果只有一个派生类但多个派生类不起作用,则此代码有效。感谢帮助。

class Base
{
  public:
   virtual int test1(int a,int b) = 0;
   virtual int test2 (int c, int d) = 0;
   virtual ~Base() {}
 };

class Derived1
  : public Base
 {
   public:
   int test1(int a, int b) { return a+b; }
};

class Derived2
 : public Base
{
  public:
  int test2(int c, int d) { return c+d; }
};
struct BaseWrap
  : Base, python::wrapper<Base>
{
  int test1(int a , int b) 
  {
     return this->get_override("test")(a, b);
   }
  int test2(int c ,int d)
   {
     return this->get_override("test")(c, d);
    }
};

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

  python::class_<Derived1, python::bases<Base> >("Derived1")
   .def("test1", &Derived1::test1)
   ;

   python::class_<Derived2, python::bases<Base> >("Derived2")
   .def("test2", &Derived2::test2)
   ;   
}
4

1 回答 1

2

错误消息表明既Derived1不能也Derived2不能实例化,因为它们是抽象类:

  • Derived1有一个纯虚函数:int Base::test2(int, int).
  • Derived2有一个纯虚函数:int Base::test1(int, int).

当其中任何一个通过 暴露时boost::python::class_,应该会发生编译器错误。class_'sHeldType默认为公开的类型,并且HeldType在 Python 对象中构造。因此,python::class_<Derived1, ...>将实例化试图创建动态类型为 的对象的 Boost.Python 模板Derived1,从而导致编译器错误。

此错误不会出现BaseWrap,因为BaseWrap实现了所有纯虚函数。该boost::python::pure_virtual()函数指定 Boost.Python 将在调度期间引发“纯虚拟调用”异常,如果该函数尚未在 C++ 或 Python 中被覆盖。

于 2013-11-04T17:21:13.787 回答