C++中的constructor function与destructor function问题

 

class father

{

  public: father()

 {

     x=new int;

 cout<<"father constructor running\n"; 

 }

~father()

{

  delete x;

 cout<<"father destructor running\n";

}

private:

  int *x;

};

class son :public father

{

  public : son()

{

   y= new y;

cout<<"son constructor running\n";

}

~son()

{

  delete y;

cout<<"son destructor running \n";

}

private :

   int *y;

};

int main()

{

   father *test=new son();

   delete test;

 return 0;

}

运行结果:

这难道不会导致内存泄漏吗???

改一下main函数

int main()

{

.....

delete (son*)test;

}

运行结果:

貌似这样就可以解决问题了。

当你把destructor function 加上virtual的话,也可以解决问题

附加上一句:我用的是vs2010的编译器

posted @ 2012-04-08 11:41  hackj  阅读(192)  评论(0)    收藏  举报