代码在虚拟函数和继承方面未按预期工作

Code not working as expected with virtual function and inheritance

本文关键字:工作 方面未 继承 虚拟 函数 代码      更新时间:2023-10-16

下面的代码显示基类(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基类中被声明为 virtual,并且所有派生类都继承了该基类。他们没有明确声明其覆盖为虚拟并不重要。