码迷,mamicode.com
首页 > 其他好文 > 详细

构造函数中的静态变量

时间:2015-07-18 13:54:06      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

  1. #ifndef SELF_SUM_H
  2. #define SELF_SUM_H
  3. #include<iostream>
  4. unsigned int Sum_solution1(int n_value);
  5. class SumDefaultConstruct{
  6. private:
  7. static unsigned int countN;
  8. static unsigned int sumN;
  9. public:
  10. SumDefaultConstruct(){
  11. countN++;
  12. sumN+=countN;
  13. }
  14. static void reSet(){
  15. countN=0;
  16. sumN=0;
  17. }
  18. static unsigned int getSum(){
  19. return sumN;
  20. }
  21. };
  22. unsigned int SumDefaultConstruct::countN=0;
  23. unsigned int SumDefaultConstruct::sumN=0;
  24. unsigned int Sum_solution1(int n_value){
  25. if(n_value==0){
  26. return 0;
  27. }
  28. SumDefaultConstruct::reSet();
  29. SumDefaultConstruct *ptr=new SumDefaultConstruct[n_value];
  30. delete[] ptr;
  31. ptr=NULL;
  32. return SumDefaultConstruct::getSum();
  33. }
  34. #endif
  1. unsigned int SumDefaultConstruct::countN=0;
  2. unsigned int SumDefaultConstruct::sumN=0;
以前是怱略了这两句,对于C++,一段时间不编就忘了。
在C++中的静态变量只是声明了,但是没有定义。还没有分配存储空间,静态变量一般和全局变量的空间差不多。
那么我们需要在类外部定义或初使化这两个静态变量,也就是分配空间啰。
因为静态变量是属于所有对象的。所心也不可以用this访问,因为这个对象内部并没有为它分配存储空间,而是在全局的变量存储区。




构造函数中的静态变量

标签:

原文地址:http://www.cnblogs.com/yml435/p/4656535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!