类中静态成员的作用就是在该类的所有对象之中共享这个变量。
如:用来对该类的对象进行计数
1 // the use of static member of class
2 #include <iostream>
3 class A {
4 private:
5 static int count;
6 public:
7 A() {
8 count++;
9 }
10
11 ~A() {}
12
13 inline int get_count() __attribute__((always_inline)) {
14 return count;
15 }
16 };
17
18 int A::count = 0;
19
20 int main() {
21 A a1;
22 A a2;
23 A a3;
24 A a4;
25 A a5;
26 A a6;
27 A a7;
28 A a8;
29 std::cout << "count = " << a1.get_count() << std::endl;
30 }
执行:
count = 8
欢迎关注公众号Magicio
浙公网安备 33010602011771号