重载new和delete后调用构造函数和析构函数顺序
2011-12-16 21:34 javaspring 阅读(572) 评论(0) 编辑 收藏 举报环境:VS2010
问题;探索重载new和delete后构造函数、修改函数的调用顺序
代码:
#include <iostream> using namespace std; class C { float x,y; public: C(){ cout<<"调用构造函数"<<endl; } ~C(){ cout<<"调用析构函数"<<endl; } void show() { cout<<"x="<<x<<'\t'<<"y="<<y<<'\n'; } void *operator new (size_t s) { void *p=new char [s]; cout<<"调用函数new(size_t s),分配空间为:"<<s<<'\n'; return p; } void operator delete (void *p) { delete (p); cout<<"调用函数delete(void *p)\n"; } }; int main(void) { C *p1; p1=new C; p1->show(); delete(p1); getchar(); return 0; }执行结果:
总结:重载后new时先分配空间,再调用构造函数,delete时先调用析构函数,后释放空间。