#include <iostream>using namespace std;class Base{public: virtual void foo(void) { std::cout << "Base::foo()" << std::endl; } virtual void doo(void) { std::cout << "Base::doo()" << std::endl; }};class Derived: public Base{public: void foo(void) { //foo(); // 错误。递归调用自己,即 Derived::foo() Base::foo(); // 明确告诉编译器,调用的是 Base::foo(), 而不是自己 std::cout << "Derived::foo()" << std::endl; } virtual void doo(void) { Base::doo(); std::cout << "Derived::doo()" << std::endl; }};class Derived2 : public Derived{ virtual void doo(void) { Derived::doo(); std::cout << "Derived2::doo()" << std::endl; }};class Derived3 : public Derived2{ virtual void foo(void) { Derived2::foo(); std::cout << "Derived3::foo()" << std::endl; }};int main(/* int argc, char *argv[] */){ Derived3 *d = new Derived3; Base *b = d; b->foo(); cout << "------------------------" << endl; b->doo(); b = nullptr; delete d; d = nullptr; return 0;}程序输出:
结论:
1.派生类虚函数调用基类版本时,必须显式使用作用域操作符。2.多态时,在虚函数继承链上,如果某个子类没有覆盖虚函数,则调用亲缘最近的父类版本。最佳做法,还是每个子类都实现。
参考资料:
1.派生类虚函数调用基类版本
http://blog.csdn.net/glx2012/article/details/8254623
新闻热点
疑难解答