fn1()是虚函数;DerivedClass也有成员函数 fn1(),fn2()。在主函数中声明一个DerivedClass的对象,分别用BaseClass和DerivedClass的指针指向DerivedClass的对象,并通过指针调用fn1(),fn2(),观察运行结果。
#include <iostream>
using namespace std;
class BaseClass
{
public:virtual void fn1() {cout << "调用基类的虚函数 fn1()" << endl;}void fn2(){cout << "调用基类的非虚函数 fn2()" << endl;}};class DerivedClass : public BaseClass
{
public: void fn1(){cout << "调用派生类的函数 fn1()" << endl;}void fn2(){cout << "调用派生类的函数 fn2()" << endl;}
};void main()
{DerivedClass aDerivedClass;DerivedClass *pDerivedClass = &aDerivedClass;BaseClass *pBaseClass = &aDerivedClass;pBaseClass->fn1();pBaseClass->fn2();pDerivedClass->fn1();pDerivedClass->fn2();
}
在BaseClass中声明虚析构函数,在主函数中将一个动态分配的DerivedClass的对象地址赋给一个BaseClass的指针,然后通过指针释放对象空间。运行观察结果
#include <iostream>
using namespace std;
class BaseClass
{
public:virtual ~BaseClass(){cout << "虚函数 ~BaseClass()" << endl;}};class DerivedClass : public BaseClass
{
public:virtual ~DerivedClass(){cout << "虚函数 ~DerivedClass()" << endl;}
};int main()
{BaseClass *p;p = new DerivedClass;delete p;
}