gpt4 book ai didi

python - 导出到 Python 的虚拟和派生 C++ 类

转载 作者:行者123 更新时间:2023-11-30 03:51:18 24 4
gpt4 key购买 nike

我有一个虚拟基类:

class H{
public:
H(); // the implementation is in .cpp file, so this is not pure virtual
virtual ~H();
//... // other members
};

和派生类:

class Hm : public H{
public:
Hm(){ /*define constructor*/ }
...
void method1();
};

我使用 Boost.Python 将两个类导出到 Python。接下来,假设还有另一个类 X,它包含一个 H 类型的变量:

class X{
public:
X(){ /*define constructor*/ }
H h; // data member
//...
};

类和变量 h 也暴露给 Python。现在,在 Python 中我可以这样做:

x = X()  # construct the object x of type X
x.h = Hm() # assign the data member of type H to the object of type Hm
# no problem with that, because of the inheritance

现在,问题是——我如何从 x.h 调用类 Hm (method1) 的方法?对象x.h的类型为H,没有定义派生类method1的方法。所以调用

x.h.method1()

给出错误

那么,有什么办法可以做到吗?或者我可能需要更改类的设计。在后一种情况下,对于我在上述示例中尝试执行的利用类型,最佳方式是什么?

最佳答案

您在这里遇到的行为称为切片。 “切片”是指将派生类的对象分配给基类的实例,从而丢失部分信息 - 其中一些信息被“切片”掉。

如果您希望能够调用method1(),您需要:

  • Hm 作为成员添加到 X 类
  • H*作为成员添加到class X,并将虚拟或纯虚拟method1()添加到class H

关于如何将指针公开给 python 的一些想法:herehere

关于python - 导出到 Python 的虚拟和派生 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31350245/

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