#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ class someThing { public: someThing(){std::cout << "someThing's construction function" << std::endl;} ~someThing(){std::cout << "someThing's destructor function" << std::endl;} }; class parent { public: parent(){std::cout << "parent's construction function" << std::endl;} ~parent(){std::cout << "parent's destructor function" << std::endl;} }; class child : public parent { public: child(){std::cout << "child's construction function" << std::endl;} ~child(){std::cout << "child's destructor function" << std::endl;} private : someThing nameChild; }; int main(int argc, char** argv) { child myChild; return 0; }
结果是:
parent's construction function
someThing's construction function
child's construction function
child's destructor function
someThing's destructor function
parent's destructor function
可见构造函数是从父类开始的,然后才是子类的构造函数。
析构函数刚好相反
这里存在一个问题就是:当我们声明一个指向parent的指针访问chlid的对象并且删除这个指针的时候就会发现,出问题啦!
parent* myChlid = new child;
delete myChlid;
结果是:
parent's construction function
someThing's construction function
child's construction function
parent's destructor function
因为当我们delete一个指针时,他是仅仅delete指向的那个类,这使得整个析构函数调用链断了。怎么解决这个问题呢?
我们只需要使得每个析构函数为virtual即可
virtual ~someThing(){std::cout << "someThing's destructor function" << std::endl;}
virtual ~parent(){std::cout << "parent's destructor function" << std::endl;}
virtual ~child(){std::cout << "child's destructor function" << std::endl;}
这样的话就可以得到我们期望的结果:
parent's construction function
someThing's construction function
child's construction function
child's destructor function
someThing's destructor function
parent's destructor function
最够贴上完整的代码:
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ class someThing { public: someThing(){std::cout << "someThing's construction function" << std::endl;} virtual ~someThing(){std::cout << "someThing's destructor function" << std::endl;} }; class parent { public: parent(){std::cout << "parent's construction function" << std::endl;} virtual ~parent(){std::cout << "parent's destructor function" << std::endl;} }; class child : public parent { public: child(){std::cout << "child's construction function" << std::endl;} ~child(){std::cout << "child's destructor function" << std::endl;} private : someThing nameChild; }; int main(int argc, char** argv) { parent* myChlid = new child; delete myChlid; return 0; }
结果是:
parent's construction function someThing's construction function child's construction function child's destructor function someThing's destructor function parent's destructor function