2013-11-01 66 views
2

如何使用boost python使用純虛函數實現多重聯機。我得到的錯誤是'Derived1'不能立即抽象類。和'Derived2'不能實例化抽象類。如果只有一個派生類但多於一個派生類不工作,則此代碼正在工作。感謝幫助。使用純虛函數的boost python中的多個派生類

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) 
    ; 
} 
+1

確切的錯誤是什麼? – kashif

+1

錯誤是錯誤C2259:'Derived1':無法實例化抽象類錯誤C2259:'Derived2':無法實例化抽象類 – user2696156

+0

「此代碼正在工作,如果只有一個派生類」這是否意味着您可以具有相同的確切定義對於'Base',對Derived1'具有相同的確切定義,但是取出Derived2'的定義,並保留'BaseWrap'的定義,它的工作原理? –

回答

2

該錯誤消息表示既不Derived1也不Derived2可以被實例化,因爲它們是抽象類:

  • Derived1具有純虛函數:int Base::test2(int, int)
  • Derived2有一個純虛函數:int Base::test1(int, int)

當其中任何一個通過boost::python::class_暴露時,應該發生編譯器錯誤。 class_HeldType默認爲正在公開的類型,並且HeldType在Python對象內構建。因此,python::class_<Derived1, ...>將實例化Boost.Python模板,該模板嘗試創建一個動態類型爲Derived1的對象,從而導致編譯器錯誤。

由於BaseWrap實現了所有純虛函數,所以該錯誤不會與BaseWrap一起出現。 boost::python::pure_virtual()函數指定如果函數未被C++或Python重寫,Boost.Python將在調度過程中引發「純虛擬調用」異常。

相關問題