static在C++中的理解

 C++中增加了类的概念.所以static 在C++中除了有C的特点外,还有就是在类中的特性了.

1.For data members, static indicates  that only one piece of storage for member data exists for all objects of a class.

 

2.you can also create static member functions that ,like static data members,work for the class as a whole rather than a particular object of a class.Because they have no this pointer, static member functions can neither access non-static data members nor call non-static member functions.

 

完美体现这两个特性的例子,就是Singleton设计模式的实现.

  1. #include <iostream>
  2. using namespace std;
  3. class Singleton
  4. {
  5. private:
  6.     int i;
  7.      Singleton(int ii);
  8.      Singleton(Singleton &);//防止 Singleton s=*Singleton::GetInstance();
  9.                             //Singleton s(*Singleton::GetInstance());
  10.     static Singleton one;
  11.     
  12. public:
  13.     static Singleton * GetInstance();
  14.     int GetVal() const
  15.     
  16. };
  17. Singleton::Singleton(int ii): i(ii)
  18. {
  19. }
  20. int Singleton::GetVal() const
  21. {
  22.     return i;
  23. }
  24. Singleton Singleton::one(3);
  25. Singleton * Singleton::GetInstance()
  26. {
  27.     return &one;
  28. }
  29. int main()
  30. {
  31.     //Singleton s(3); 此句发生错误
  32.     //error C2248: 'Singleton::Singleton' : cannot access private member declared in class 'Singleton'
  33.     // see declaration of 'Singleton::Singleton'
  34.     cout<<Singleton::GetInstance()->GetVal()<<endl;
  35.  return 0;
  36. }

总结:由一个static数据成员和一个static函数成员实现了Singleton设计模式.

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值