• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LyonLys
愿意在角落唱沙哑的歌 再大声也都是给你 请用心听 不要说话 Contact me via E-mail: lyon.lys@gmail.com
博客园    首页    新随笔    联系   管理    订阅  订阅

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

posted @ 2014-06-11 00:57  LyonLys  阅读(1325)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3