gpt4 book ai didi

c++ - 错误 C2259 : "Derived" cannot instantiate abstract class

转载 作者:太空宇宙 更新时间:2023-11-04 11:46:49 24 4
gpt4 key购买 nike

如何使用 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)
;
}

最佳答案

纯虚函数的调用方式与非纯虚函数相同。唯一的区别是作为纯虚拟 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() 会引发异常已妥善 dispatch 。

关于c++ - 错误 C2259 : "Derived" cannot instantiate abstract class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com