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设计模式的实现.
- #include <iostream>
- using namespace std;
- class Singleton
- {
- private:
- int i;
- Singleton(int ii);
- Singleton(Singleton &);//防止 Singleton s=*Singleton::GetInstance();
- //Singleton s(*Singleton::GetInstance());
- static Singleton one;
- public:
- static Singleton * GetInstance();
- int GetVal() const;
- };
- Singleton::Singleton(int ii): i(ii)
- {
- }
- int Singleton::GetVal() const
- {
- return i;
- }
- Singleton Singleton::one(3);
- Singleton * Singleton::GetInstance()
- {
- return &one;
- }
- int main()
- {
- //Singleton s(3); 此句发生错误
- //error C2248: 'Singleton::Singleton' : cannot access private member declared in class 'Singleton'
- // see declaration of 'Singleton::Singleton'
- cout<<Singleton::GetInstance()->GetVal()<<endl;
- return 0;
- }
总结:由一个static数据成员和一个static函数成员实现了Singleton设计模式.