2013-10-24 86 views
1

我怎麼能通過使用boost python調用派生類中的純虛函數。我得到的是,無法實例化抽象基類。示例代碼如下:錯誤C2259:「派生」不能實例化抽象類

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

什麼是'wrapper'? – Angew

+1

wrapper是來自Boost python的關鍵字。 – user2696156

+0

有[sscce](http://sscce.org/)的示例用法和錯誤的機會? –

回答

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,表示已經調用了純虛函數。因此,Spam對象上的test()引發異常,Egg對象上的test()正確分派。