免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2304 | 回复: 5
打印 上一主题 下一主题

菜鸟求解 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-14 14:00 |只看该作者 |倒序浏览

  1. #include<iostream>
  2. #include <stdio.h>
  3. class Sequence{
  4.     public:
  5.         Sequence(int count=10,string name = "abc");
  6.         void show();
  7.         ~Sequence();

  8.         int* _content;
  9.         int _count;
  10.         string _name;

  11. };

  12. Sequence::Sequence(int count,string name){
  13.     _count = count;
  14.     _content=new int[count];
  15.     _name = name;
  16.     for(int i=0;i<count;i++){
  17.         _content[i]=i;
  18.     }
  19.     this->show();
  20.     cout<<"constructor  over!!"<<endl;
  21. }

  22. Sequence::~Sequence(){
  23.     cout << "execute ---"<<_name;
  24.     delete [] _content;
  25. }

  26. void Sequence::show(){
  27.     cout<<endl<<"{";
  28.     for(int i=0;i<_count;i++){
  29.         cout<<_content[i]<<" ";
  30.     }
  31.     cout<<"name = "<<_name<<endl;
  32.     cout<<"}"<<endl;
  33. }

  34. int main(){
  35.     Sequence s1;//这里有疑问,运行结果并没有调用析构函数,为啥啊?
  36.     //s1.~Sequence();
  37.     //s1.show();
  38.     //s1.~Sequence();
  39.     //s1.show();
  40.     //s1 = Sequence(3,"s1");
  41.     //s1.show();
  42.     //Sequence(5,"hello");
  43.     system("pause");
  44. }

复制代码

论坛徽章:
0
2 [报告]
发表于 2011-06-14 14:16 |只看该作者
....

void test()
{
Sequence s1;
}

int main(){
    test();
    system("pause");
}
...

论坛徽章:
0
3 [报告]
发表于 2011-06-14 14:19 |只看该作者
哇 果然正确了 但是为啥啊? 能讲下嘛,或者推荐一本书看看,谢谢了!

论坛徽章:
0
4 [报告]
发表于 2011-06-14 14:24 |只看该作者
C++对象模型

论坛徽章:
0
5 [报告]
发表于 2011-06-15 09:25 |只看该作者
你把 system("pause") 去掉试试?就应该行了。

pause 的时候,  object 还没有被销毁,导致对象没有析构。
而 2L 的方法中, 对象的生成和销毁在另外一个函数中执行,所以构造函数和析构函数都得以执行。

关键在于,保证对象可以正常销毁。

论坛徽章:
0
6 [报告]
发表于 2011-06-15 09:42 |只看该作者
Sequence s1 in the main function is local variable, whose lifetime will over when the main runs to end, so the deconstruct function will be called when main runs to the end.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP