class Derived : public Base { public: virtual void f(float x){ cout 〈〈 "Derived::f(float) " 〈〈 x 〈〈 endl. } void g(int x){ cout 〈〈 "Derived::g(int) " 〈〈 x 〈〈 endl. } void h(float x){ cout 〈〈 "Derived::h(float) " 〈〈 x 〈〈 endl. } }.
示例8-2-2(a)成员函数的重载、覆盖和隐藏 据作者考察,很多C 程序员没有意识到有“隐藏”这回事。由于认识不够深刻,“隐藏”的发生可谓神出鬼没,常常产生令人迷惑的结果。 示例8-2-2(b)中,bp和dp指向同一地址,按理说运行结果应该是相同的,可事实并非这样。 void main(void) { Derived d. Base *pb = &.d. Derived *pd = &.d. // Good : behavior depends solely on type of the object pb-〉f(3.14f). // Derived::f(float) 3.14 pd-〉f(3.14f). // Derived::f(float) 3.14 // Bad : behavior depends on type of the pointer pb-〉g(3.14f). // Base::g(float) 3.14 pd-〉g(3.14f). // Derived::g(int) 3 (surprise!)