代码

#include <iostream>
using namespace std; class BaseClass{ public: void fn1(); void fn2(); }; void BaseClass::fn1(){ cout << "调用基类的函数 fn1()" << endl; } void BaseClass::fn2(){ cout << "调用基类的函数 fn2()" << endl; } class DerivedClass : public BaseClass{ public: void fn1(); void fn2(); }; void DerivedClass::fn1(){ cout << "调用派生类的函数 fn1()" << endl; } void DerivedClass::fn2(){ cout << "调用派生类的函数 fn2()" << endl; } int main() { DerivedClass aDerivedClass; DerivedClass *pDerivedClass = &aDerivedClass; BaseClass *pBaseClass = &aDerivedClass; aDerivedClass.fn1(); aDerivedClass.fn2(); cout << "--------------" << endl; pBaseClass->fn1(); pBaseClass->fn2(); cout << "--------------" << endl; pDerivedClass->fn1(); pDerivedClass->fn2(); }

结果可见,把子类的对象的地址赋值给父类的指针,执行同名的函数体只会执行父类的

调用派生类的函数 fn1() 调用派生类的函数 fn2() -------------- 调用基类的函数 fn1() 调用基类的函数 fn2() -------------- 调用派生类的函数 fn1() 调用派生类的函数 fn2()