#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class Person
{
public:
Person(string name = "jim")
{
m_name = name;
cout << "调用了Person()" << endl;
}
~Person()
{
cout << "调用了析构函数~Person()" << endl;
}
void play()
{
cout << "person--play" << endl;
cout << m_name << endl;
}
protected:
string m_name;
};
class Soldier :public Person
{
public:
Soldier(string name = "james", int age = 20)
{
m_name = name;
m_age = age;
cout << "调用了soldier()" << endl;
}
~Soldier()
{
cout << "调用了析构函数~Soldier()" << endl;
}
void work()
{
cout << m_name << endl;
cout << m_age << endl;
cout << "soldier--work()" << endl;
}
protected:
int m_age;
};
int main(void)
{
Person *P1=new Soldier; //用person(父类)指针指向从堆中分配来的soldier(子类)对象
P1->play();
delete P1;//销毁父类对象指针P1
P1 = NULL;
system("pause");
return 0;
}
观察现象:
解决方法:
在子类和父类的析构函数之前加上virtual
运行结果: