BOOST.PYTHON中的基础和派生类

Base and derived classes in Boost.Python

本文关键字:派生 PYTHON BOOST      更新时间:2023-10-16

我有两个类 - 假设A和B。B类是A的子类,都具有函数H,因此:

class A{
  public:
  A(){;;}  // ctor
  virtual ~A(){ ;; } // destr.
  virtual double H(int i,int j){ 
    std::cout<<"Calling the base function H. Level is too abstractn";
    exit(0);
    return 0.0;
  }// H
};// class A

派生的B类是:

class B : public A{
  public:
  B(){;;}  // ctor
  ~B(){ ;; } // destr.
  double H(int i,int j){ 
    return 1.0;
  }// H
};// class B

我还具有将类型类型的参数的函数:

double f(A x){
  return x.H(1,1); 
}

我想将派生类型B的对象用作Python中此函数的参数。因此,我导出了这两个类别和此处解释的功能:

BOOST_PYTHON_MODULE(modAB){
  class_<A>("A", no_init);
  class_<B, bases<A> >("B", init<>())
    .def("H", &B::H)
  ;    
  def("f", &f);
}

所以在python中我做:

>>> from modAB import *
>>> x = B()
>>> res = f(x)

作为输出,我看到该方法H是从基类调用的,而不是从我预期的派生类中调用:

Calling the base function H. Level is too abstract

所以,我的问题是我在哪里错了,我可能想念什么?

double f(A x)通过值传递 x,因此传递类型B的对象将切除其派生的虚拟函数。

要修复它,您需要通过const A&

double f(const A& x)