gpt4 book ai didi

c++ - 代码无法按预期使用虚函数和继承

转载 作者:行者123 更新时间:2023-11-30 03:15:20 26 4
gpt4 key购买 nike

下面的代码显示基类 (GrandParent) 有一个虚函数 (show()) 和两个虚拟派生类(Parent1 和 Parent2),每个派生类都有自己的 show() 实现。 Child 类继承了 Parent1 和 Parent2 并实现了它自己的 show() 版本。

在下面的代码中,我有一个新对象 (Parent2 *objP = new Child();) 并调用 objP->show()。我希望这会调用 Parent2 的 show() 函数(并返回 9)。然而,它实际上是在调用 Child 的 show() 函数(因此返回 7)。

我知道 show() 是 GrandParent 的虚函数,但它不是 Parent2 的虚函数。因此混淆了为什么 objP->show() 调用 Child 的 show() 而不是 Parent2。

感谢您的帮助。

class GrandParent {
public:
int virtual show() { return 10; }
};


class Parent1 : public virtual GrandParent {
public:
int show() { return 1; }
};

class Parent2 : public virtual GrandParent {
public:
int show() { return 9; }
};

class Child : public Parent1, public Parent2 {
public:
Child(){}
int show() { return 7; }
};

int main() {
GrandParent *objGrand = new Child();
GrandParent *objGrand1 = new Parent1();
Parent2 *objP = new Child();
Child *objChild = new Child();

cout << objGrand->show() << endl;// get 7 as expected
cout << objP->show() << endl; // get 7 instead of 9 expected
cout << objChild->show() << endl; // get 7 as expected
cout << objGrand1->show() << endl; // get 1 as expected

return 0;
}

最佳答案

show() 函数在所有类中都是虚函数。它在 GrandParent 基类中被声明为虚拟的,所有派生类都继承它。他们没有明确声明他们的覆盖是虚拟的并不重要。

关于c++ - 代码无法按预期使用虚函数和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57134708/

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