[英]C++ multilevel inheritance function calls
Consider multilevel inheritance between C++ classes. 考虑C ++类之间的多级继承。 Consider:
考虑:
struct A {
void Dummy1() { }
};
struct B : A {
void Dummy1() { }
};
struct C : B {
void Dummy() {
Dummy1();
}
void Dummy1() { }
};
struct D : C {
void Dummy1() { }
};
struct E : D {
void Dummy1() { }
};
Given: 鉴于:
E e;
e.Dummy();
I want to know which Dummy1 would be called. 我想知道哪个Dummy1将被调用。 The one defined in class
C
or the one defined in class E
? C
类中定义的一个或E
类中定义的一个?
Also, I get very confused in function call made in multilevel inheritance, like in case of virtual functions etc. Can some one suggest a book or article which can help me in understanding this. 另外,我对在多级继承中进行的函数调用感到非常困惑,例如在虚函数等情况下。有人可以建议一本书或一篇文章来帮助我理解这一点。 I googled a lot but was not able to find anything helpful.
我在Google上搜索了很多,但找不到任何有用的信息。
Thanks in advance. 提前致谢。
I want to know which
Dummy1
would be called.我想知道哪个
Dummy1
将被调用。 The one defined in classC
or the one defined in classE
?C
类中定义的一个或E
类中定义的一个?
Given your code, it will call the one defined in C
. 给定您的代码,它将调用
C
定义的代码。
If you want it to call the one defined in E
, you'll have to make Dummy1
a virtual
function. 如果希望它调用
E
定义的函数,则必须使Dummy1
成为virtual
函数。
The principle you want to learn is called polymorphism . 您要学习的原理称为多态 。
If the Dummy1()
is defined as virtual
in all classes then the version will be used which is defined in the exact class of the object, ie in your case E::Dummy()
. 如果在所有类中都将
Dummy1()
定义为virtual
,则将使用在对象的确切类中定义的版本,即您的情况E::Dummy()
。
However in your code it is not virtual
that's why you will have C::Dummy()
called 但是,在您的代码中,它不是
virtual
,所以您将调用C::Dummy()
Mind that most compilers will give a warning that you're overriding a function if virtual
is not provided when inheriting (and function definition matches) 请注意,如果在继承时(且函数定义匹配)未提供
virtual
,则大多数编译器都会警告您正在覆盖函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.