CSDN首页 空间 新闻 论坛 Blog 下载 读书 网摘 搜索 .NET Java 视频 接项目 求职 在线学习 买书 程序员 通知
山寨机中的战斗机! 程序优化工程师到底对IT界有没有贡献
CSDN社区
搜索 收藏 打印 关闭
CSDN社区 >  C/C++ >  C语言

对象生成问题求解

楼主brave_heart(白菜)2002-04-17 21:49:39 在 C/C++ / C语言 提问

class   sam  
  {  
  protected:  
      ~sam()   {}  
  public:  
      sam()   :   i(0)  
      {}  
   
      int   i;  
  };  
   
  sam   s;     //   error  
   
  sam*   ps   =   new   sam;   //   ok  
   
  why   compiler   complain   about   the   first   statement?  
   
  Thanks   in   advance  
  问题点数:20、回复次数:3Top

1 楼T34(我是坦克我怕谁)回复于 2002-04-17 22:11:10 得分 12

I   think,   in   the   1st   case,   the   compiler   generate   s   on   the   stack   for   you,   and   will   call   destructor   for   you   when   the   life   of   s   is   ended.  
  suppose   you   have   the   following   code  
  void   f()  
  {  
          sam   s;  
          some   action;  
  }  
   
  the   compiler   will   translate   it   into   something   like   this  
  void   f()  
  {  
          allocate   s   on   stack  
          sam::sam(&s);  
          some   action;  
          sam::~sam()    
  }  
  so   it   complains   for   lacking   of   desctuctor.  
   
  in   the   2nd   case,   you   new   a   sam   class   object   on   heap,   so   it   is   up   to   you   to   free   it,   and   no   error   occurs,   but   of   course   delete   ps   will   not   be   safe.Top

2 楼rovoboy(魂之猎人)回复于 2002-04-17 22:12:46 得分 8

My   English   Bad.  
  May   Some   Language   Mistake.  
   
  delete   ps;  
  Will   Fail   Because   Of   The   Same   Reason   As   sam   a  
   
  sam   s;  
  Compiler   Confirms   That   You   Can   Do   sam()   &   ~sam()  
   
  sam*   ps   =   new   sam;  
  Compiler   Only   Confirms   That   You   Can   Do   sam()  
   
  delete   ps;  
  Compiler   Only   Confirms   That   You   Can   Do   ~sam()  
  Top

3 楼wlz47(秋水沉舟)回复于 2002-04-17 22:20:44 得分 0

if   use  
   
  delete   ps;       //   compile   error   hereTop

相关问题

  • csdn菜单树生成方法求解
  • 生成问题,高分求解
  • 动态生成对象
  • 100分求解,如何动态生成对话框
  • 重分求解!关于动态生成的控件
  • web部署安装项目的生成错误 求解
  • ★★200分求解★★ DELPHI中调用SQL生成器
  • 高分求解!怎么保持DataGrid动态生成列的ViewState?
  • 高分求解一生成有效字符串算法
  • 高分求解VB.NET生成WORD文档时可视化问题

关键词

  • ps
  • sam
  • compile
  • confirms
  • delete

得分解答快速导航

  • 帖主:brave_heart
  • T34
  • rovoboy

相关链接

  • C/C++ Blog
  • C/C++类图书
  • C/C++类源码下载

广告也精彩

反馈

请通过下述方式给我们反馈
反馈
提问
网站简介|广告服务|VIP资费标准|银行汇款帐号|网站地图|帮助|联系方式|诚聘英才|English|问题报告
北京创新乐知广告有限公司 版权所有, 京 ICP 证 070598 号
世纪乐知(北京)网络技术有限公司 提供技术支持
Copyright © 2000-2008, CSDN.NET, All Rights Reserved
GongshangLogo