【问题标题】:error C2259: "Derived" cannot instantiate abstract class错误 C2259:“派生”无法实例化抽象类
【发布时间】:2013-10-24 10:39:13
【问题描述】:

如何使用 boost python 在派生类中调用纯虚函数。我得到的错误是无法实例化抽象基类。示例代码如下:

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

【问题讨论】:

  • wrapper 是 Boost python 的关键字。
  • 是否有机会获得sscce 的示例用法和错误?
  • 问题是如何在BOOST_PYTHON_MODULE中编写访问派生类的测试函数的语句。

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


【解决方案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

当在继承自 example.Base 但未实现 test() 方法的类型上调用 test() 时,Boost.Python 将引发 RuntimeError 指示已调用纯虚函数。因此,Spam 对象上的test() 引发异常,而Egg 对象上的test() 被正确调度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 2019-03-13
    • 1970-01-01
    相关资源
    最近更新 更多