Guest User

Untitled

a guest
Aug 19th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. how a vector of objects (with static members) is constructed
  2. 1 2 3 4 5
  3. 6 7 8 9 10
  4.  
  5. 1 2 3 4 5
  6. 6 6 6 6 6
  7.  
  8. // ==== test.h =====
  9. using namespace std;
  10.  
  11. void test();
  12.  
  13. class Record{
  14. static int total_number;
  15. int id;
  16. public:
  17. Record();
  18. void show() {std::cout << id << " "; }
  19. };
  20.  
  21.  
  22. // ==== test.cpp ====
  23. #include "stdafx.h"
  24. #include <iostream>
  25. #include <vector>
  26. #include "test.h"
  27. using namespace std;
  28.  
  29. Record::Record(){
  30. total_number += 1;
  31. id = total_number;
  32. }
  33.  
  34. void test(){
  35.  
  36. const int vec_length = 5;
  37. Record a[vec_length];
  38.  
  39. for (unsigned int i=0; i<vec_length; i++)
  40. a[i].show();
  41.  
  42. cout << endl;
  43.  
  44. vector<Record> vr(vec_length);
  45. for (unsigned int i=0; i<vr.size(); i++)
  46. vr[i].show();
  47. cout << endl;
  48. }
  49.  
  50.  
  51. // ==== main.cpp =====
  52. #include "stdafx.h"
  53. #include <iostream>
  54. #include "test.h"
  55. using namespace std;
  56.  
  57. int Record::total_number = 0;
  58.  
  59. int _tmain(int argc, _TCHAR* argv[])
  60. {
  61. test();
  62. return 0;
  63. }
  64.  
  65. std::vector<Record> v(5, Record());
  66.  
  67. std::vector<Record> v(5);
  68.  
  69. Record::Record() : id(++total_number) {}
  70.  
  71. Record::Record(const Record &other) : id(other.id) {}
Add Comment
Please, Sign In to add comment