对象析构顺序问题,回帖有分
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
class person
{
public:
int age;
person(){}
virtual ~person(){
cout<<"~person"<<endl;
}
// virtual void f() {}
};
class man : public person
{
public:
int sex;
man(){}
virtual ~man(){
cout<<"~man"<<endl;
}
};
class woman : public person
{
public:
int tall;
woman(){}
virtual ~woman(){
cout<<"~woman"<<endl;}
};
int main(int argc, char* argv[])
{
printf("Hello World!\n");
vector<person*> vect;
man* p1 = new man;
p1->age = 10;
p1->sex = 2;
woman* p2 = new woman;
p2->tall = 100;
p2->age = 30;
vect.push_back(p1);
vect.push_back(p2);
for (vector<person*>::const_iterator iter = vect.begin(); iter != vect.end(); iter++) {
if (man* pMale = dynamic_cast<man*>(*iter)) {
cout << pMale->sex << endl;
}
if (woman* pwomam = dynamic_cast<woman*>(*iter)) {
cout << pwomam->tall << endl;
}
}
for (int i = 0; i < vect.size(); i++)
{
delete vect[i];
}
vect.clear();
return 0;
}
执行结果:
Hello World!
2
100
~man
~person
~woman
~person
请按任意键继续. . .
先析构父再析构子,问题在哪???
[解决办法]
~man
~person
~woman
~person
[解决办法]
和构造顺序相反,跑一下程序就出来了
[解决办法]
先析构子类,再析构父类。
[解决办法]
听说有分就点进来了。