C++结构体中的静态变量
分享一个挺有意思的代码:
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 struct Point { 5 static int cnt; 6 Point() { 7 ++cnt; 8 cout << "There is " << cnt << " item(s)." << endl; 9 } 10 ~Point() { 11 --cnt; 12 cout << cnt << " item(s) remains." << endl; 13 } 14 } ; 15 int Point::cnt; 16 17 int main() { 18 Point a, b; 19 delete (new Point()); 20 Point c, d; 21 return 0; 22 }
java是可以直接在类中初始化的,不过C++的初始化要在结构体外完成,否则会在链接的时候发生找不到对象的错误。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 class TheOnlyInstance { 5 public: 6 static TheOnlyInstance *GetTheOnlyInstance(); 7 static int Parameter; 8 protected: 9 TheOnlyInstance() {} 10 } ; 11 12 //int TheOnlyInstance::Parameter = 2; 13 14 TheOnlyInstance *TheOnlyInstance::GetTheOnlyInstance() { 15 static TheOnlyInstance objTheonlyInstance; 16 int Parameter = 1; 17 return &objTheonlyInstance; 18 } 19 20 int main() { 21 //cout << TheOnlyInstance::Parameter << endl; 22 cout << TheOnlyInstance::GetTheOnlyInstance() << endl; 23 cout << TheOnlyInstance::Parameter << endl; 24 return 0; 25 }
——Written by Lyon