繁体   English   中英

C++ - 多级 Inheritance

[英]C++ - Multilevel Inheritance

我是 C++ 的新手,这是我第一次了解 inheritance。 我对我想讨论的多级 inheritance 有一些困惑。

考虑这段代码:

class Parent 
{
  ...
  virtual void foo() {...} // virtual function
  ...
}
class Child
  : public Parent
{
  ...
  virtual void foo() override {...} // 1
  ...
}
Class GrandChild
  : public Child
{
  ...
  void foo() override {...} // 2
  ...
}

现在,

  1. 我知道1会覆盖Parent class 方法。
  2. 但是,我不确定2 它覆盖了哪个方法, Parent中的那个还是Child中的那个?

如果我错了,请纠正我。 另外,如果有任何有用的文章,请参考我。

我会说这里的 class GrandChild覆盖了Child方法。 然而,这并不是一个非常有用的区别,因为GrandChild继承自ChildParent (间接地)。 因此,您可以执行以下所有操作:

int main() {
    Parent* p1 = new Child();
    p1->foo(); // calls Child::foo

    Parent* p2 = new GrandChild();
    p2->foo(); // calls GrandChild::foo

    Child* c = new GrandChild();
    c->foo();  // calls GrandChild::foo

    // cleanup all of the pointers
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM