#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "A()..." << endl;
this->p = new char[64];
memset(this->p,0,64);
strcpy(this->p,"A String...");
}
virtual void print()
{
cout << "A:" << this->p << endl;
}
virtual ~A() {
cout << "~A()..." << endl;
if (this->p != NULL) {
delete[] this->p;
this->p = NULL;
}
}
private:
char *p;
};
class B :public A
{
public:
B()
{
cout << "B()..." << endl;
this->p = new char[64];
memset(this->p,0,64);
strcpy(this->p,"B String...");
}
virtual void print()
{
cout << "B:" << this->p << endl;
}
virtual ~B()
{
cout << "~B()..." << endl;
if (this->p != NULL) {
delete[] this->p;
this->p = NULL;
}
}
private:
char *p;
};
void func(A *ap)
{
ap->print();
delete ap;
}
void test()
{
A *ap = new A;
func(ap);
cout << "-------------"<< endl;
B *bp = new B;
func(bp);
}
int main()
{
test();
return 0;
}
总结:
void func(A *ap)
{
ap->print();//在此发生多态
delete ap;//要使此刻ap-> ~B(),~B()再自动触发~A()
//即让此刻产生多态,要使用虚析构函数,
//不然系统默认触发~A(),不再触发~B(),会发生内存泄漏