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 }
View Code

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 }
View Code

 

 

——Written by Lyon

转载于:https://www.cnblogs.com/LyonLys/p/20140611_Lyon.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值