c++ - python 与 c++ 中的多重继承

标签 c++ python multiple-inheritance virtual-functions

这是一个 Python 和 C++ 问题。

我正在尝试多重继承,并且遇到了这个例子。

B1 B2
 \ /
  D

假设我有两个(独立的?)父类 B1、B2 和一个子类 D。我们只对D 类的对象感兴趣。

class B1:
    def f1(self):
        print "In f1"

class B2:
    def f2(self):
        self.f1()

class D (B1, B2):
    def fD(self):
        self.f2()

d = D()
d.fD()

Output: In f1

有趣的是(至少对我来说),class B2 不了解 class B1,但 f2 可以调用 self.f1() 没有问题。

我尝试在 C++ 中复制这个确切的东西,但无法使其工作,因为我不知道如何从 f2 调用 f1

class B1 {
    public:
    virtual ~B1() {}
    virtual void f1() { cout << "In f1" << endl; }
};

class B2 {
    public:
    virtual ~B2() {}
    virtual void f2() { /* What goes here?? */ }
};

class D : public B1, public B2 {
    public:
    void fD() { f2(); }
};

所以,我想知道如何/为什么 Python 可以处理这个问题,而 C++ 却不能?

此外,我们可以对 C++ 代码进行哪些最小的更改,以使其表现得像 Python 代码?

最佳答案

what minimal changes can we make to the C++ code to make it behave like the Python code?

简短回答:你不能。 B2 不知道它将形成一个子类的一部分,该子类也将 B1 作为父类(super class)。

长答案:你可以,如果你使用一些糟糕的向下转型(本质上是将 this 转换为 D*)。但这可能不是一个好主意,因为 *this 不一定是 D

关于c++ - python 与 c++ 中的多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17769188/

相关文章:

c++ - 来自 WinHTTP Async 的句柄是否需要关闭?

c++ - WM_MOUSEMOVE - 打包 x 和 y 位置

c++ - C++如何找到函数声明

c++ - C++ 中的条件运算符 "?:"

python - matplotlib:使用颜色图为表格单元格背景着色

python - 如何检查集合中是否已存在列表的 "unsorted version"?

python - 使用文本文件中的正则表达式在 Python 中的特定单词后查找单词

c++ - C++ 中的 (this != this) 是什么时候?

带有另一个基类的 python 抽象方法破坏了抽象功能

c++ - 死亡钻石和作用域解析运算符 (c++)