C++新手,在尝试搞清楚派生类基本函数的问题上遇到下面问题:
1 #include<iostream.h> 2 3 class Base 4 { 5 public: 6 virtual ~Base() 7 { 8 cout << "Base::~Base()" << endl; 9 } 10 }; 11 12 class Derived : public Base 13 { 14 public: 15 virtual ~Derived() 16 { 17 delete p_test; 18 cout << "Derived::~Derived()" << endl; 19 } 20 21 private: 22 char *p_test; 23 }; 24 25 void main(void) 26 { 27 Base *pB = new Derived; 28 delete pB; 29 }
目标输出:
Derived::~Derived()
Base::~Base()
实际输出:系统报警,内存泄露。。。
其中Base是基类,是一个多态类,基类的析构函数定义为虚函数,为的是可以像其他虚函数一样实现动态绑定。
p_test应该在构造函数初始化一下,不然可能是野指针