Static variables in constructors

Source: Internet
Author: User

  
 
  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;
Used to be mandatory slightly these two sentences, for C + +, a period of time not to forget. static variables in C + + are only declared, but not defined. No storage space has been allocated, and static variables are generally about the same as global variables. Then we need to define or initialize the two static variables outside the class, that is, allocating space. Because a static variable belongs to all objects. The heart cannot be accessed with this because the object does not allocate storage space internally, but is in the global variable store.

From for notes (Wiz)

Static variables in constructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.