C++——多级继承
C++ - Multilevel Inheritance
我是 C++ 的新手,这是我第一次学习继承。我对多级继承有些困惑,我想讨论一下。
考虑这段代码:
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
覆盖 Parent
class 方法。
- 但是,我不确定
2
。它覆盖了哪个方法,Parent
中的方法还是 Child
中的方法?
如果我错了,请纠正我。另外,如果有任何有用的文章,请向我推荐。
我会说 class GrandChild
覆盖了 Child
方法。但是,这不是一个非常有用的区别,因为 GrandChild
继承自 Child
和 Parent
(间接)。因此,您可以执行以下所有操作:
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
}
我是 C++ 的新手,这是我第一次学习继承。我对多级继承有些困惑,我想讨论一下。
考虑这段代码:
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
覆盖Parent
class 方法。 - 但是,我不确定
2
。它覆盖了哪个方法,Parent
中的方法还是Child
中的方法?
如果我错了,请纠正我。另外,如果有任何有用的文章,请向我推荐。
我会说 class GrandChild
覆盖了 Child
方法。但是,这不是一个非常有用的区别,因为 GrandChild
继承自 Child
和 Parent
(间接)。因此,您可以执行以下所有操作:
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
}