定义一个基类BaseClass,从它派生出类DerivedClass,BaseClass有成员函数fn1()、fn2(),DerivedClass也有成员函数fn1()和fn2(),在主函数中声明一个DerivedClass对象,分别用DerivedClass的对象以及BaseClass和DerivedClass的指针来调用fn1()、fn2(),观察运行结果。 1 #include2 class BaseClass { 3 public: void fn1(); void fn2(); 4 }; 5 void BaseClass::fn1() { 6 cout << "调用基类的函数fn1()" << endl; 7 } 8 void BaseClass::fn2() { 9 cout << "调用基类的函数fn2()" << endl; 10 } 11 class DerivedClass : public BaseClass { 12 public: 13 void fn1(); void fn2(); }; 14 void DerivedClass::fn1() { 15 cout << "调用派生类的函数fn1()" << endl;16 } 17 void DerivedClass::fn2() { 18 cout << "调用派生类的函数fn2()" << endl; 19 } 20 void main() 21 { 22 DerivedClass aDerivedClass; 23 DerivedClass *pDerivedClass = &aDerivedClass;24 BaseClass *pBaseClass = &aDerivedClass; 25 aDerivedClass.fn1(); 26 aDerivedClass.fn2();27 pBaseClass->fn1();28 pBaseClass->fn2();29 pDerivedClass->fn1();30 pDerivedClass->fn2();31 }