| « | November 2025 | » |  | 日 | 一 | 二 | 三 | 四 | 五 | 六 |   |  |  |  |  |  | 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |  |  |  |  |  |  |  |  
  |    公告 |  
戒除浮躁,读好书,交益友  |    
 
 
 
 
 
| Blog信息 |  
| 
 blog名称:邢红瑞的blog 日志总数:523 评论数量:1142 留言数量:0 访问次数:9731278 建立时间:2004年12月20日   |   
 
  
 
  |    | 
  
| 
  [c++]static看c++类的构造与析构 原创空间,  软件技术,  电脑与网络 
邢红瑞 发表于 2007/11/17 10:49:27   |  
| 
很久以前,我见到面试题,昨天研究static的问题,想了起来。#include "stdafx.h"#include   <fstream.h>   
class   howmany{    static   int   object_count;   public:    howmany(){     object_count++;    }    static   void   print(const   char*   msg=0)    {     if(msg)   cout<<msg<<":";     cout<<"object_cout="      <<object_count<<endl;    }    ~howmany(){     object_count--;     print("~howmany()");    }   };   int   howmany::object_count=0;   howmany   f(howmany   x){   //这里调用了一次默认copy   constructor.    x.print("x   argument   inside   f()");    return   x;//又调用了一次copy   constructor.   }   void   main()   {    howmany   h;    howmany::print("after   construction   of   h");    howmany   h2=f(h);    howmany::print("after   call   to   f()");   }  如果不运行,结果没有几个人可以说对,vc6和bcb6结果如下,vc7的结果肯定不同after   construction   of   h:object_cout=1x   argument   inside   f():object_cout=1~howmany():object_cout=0after   call   to   f():object_cout=0~howmany():object_cout=-1~howmany():object_cout=-2这是copy   constructor   的问题,一般不要用类参数,用引用就没问题。对象的逐位拷贝,所以没有调用constructor,可是对象逐位copy时,static可不是逐位copy。c++函数调用是值传递,也就是 T   t2=t1那样生成了一个局部对象,没调默认构造函数,但离开函数时却调了析构函数。其实加个拷贝构造函数,就ok了,在拷贝构造时没用构造函数,系统用了自己产生的构造函数,两种构造函数里对静态变量处理不一致。    |    
 |   
   
| 
 回复:static看c++类的构造与析构 原创空间,  软件技术,  电脑与网络 
大跌(游客)发表评论于2008/3/18 5:51:21   |  
 
 |   
   
| 
 回复:static看c++类的构造与析构 原创空间,  软件技术,  电脑与网络 
3232(游客)发表评论于2007/11/27 4:35:32   |  
| [url=http://www.huohuliulanqixiazai.com]火狐[/url] |    
 |   
 
  »  1 »  
  |