C++:是“虚拟的"继承给所有后代 [英] C++: Is "Virtual" inherited to all descendants
本文介绍了C++:是“虚拟的"继承给所有后代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设以下简单情况(注意virtual的位置)
Assume the following simple case (notice the location of virtual)
class A {
virtual void func();
};
class B : public A {
void func();
};
class C : public B {
void func();
};
下面的调用会调用 B::func()
还是 C::func()
?
Would the following call call B::func()
or C::func()
?
B* ptr_b = new C();
ptr_b->func();
推荐答案
使用指针和引用的示例.
Examples using pointers as well as reference.
使用指针
Using pointer
B *pB = new C();
pB->func(); //calls C::func()
A *pA = new C();
pA->func(); //calls C::func()
使用参考.注意最后一个电话:最重要的电话.
Using reference. Note the last call: the most important call.
C c;
B & b = c;
b.func(); //calls C::func()
//IMPORTANT - using reference!
A & a = b;
a.func(); //calls C::func(), not B::func()
这篇关于C++:是“虚拟的"继承给所有后代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文