【问题标题】:Multiple Derived Classes in boost python using pure virtual function使用纯虚函数的boost python中的多个派生类
【发布时间】:2023-03-25 07:04:01
【问题描述】:

如何通过 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)
   ;   
}

【问题讨论】:

  • 究竟是什么错误?
  • 错误是错误 C2259:'Derived1':无法实例化抽象类错误 C2259:'Derived2':无法实例化抽象类
  • "如果只有一个派生类,则此代码有效" 这是否意味着您可以对Base 有相同的精确定义,对Derived1 有相同的精确定义,但取出Derived2 的定义,并保留BaseWrap 的定义,它可以工作吗?
  • 是的,如果只有一个纯虚函数和一个派生类,那么它就可以工作。但是 2 个纯虚函数,它们在不同的派生类中实现,然后我得到了错误

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


【解决方案1】:

错误消息表明Derived1Derived2 都不能被实例化,因为它们是抽象类:

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

当其中任何一个通过boost::python::class_ 公开时,都会出现编译器错误。 class_HeldType 默认为暴露的类型,HeldType 是在 Python 对象中构造的。因此,python::class_&lt;Derived1, ...&gt; 将实例化试图创建动态类型为Derived1 的对象的 Boost.Python 模板,从而导致编译器错误。

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

【讨论】:

    猜你喜欢
    • 2018-10-14
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2018-01-25
    • 2018-05-02
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多