Written by razrlele
	   12:57                      March 2, 2016 
在C和C++语言当中都有static关键字,C语言中的功能C++全部都有,除此之外static关键字在C++的类中还有一些其他的功能。
静态存储
某些变量有些时候需要只供其所在的源文件中的函数所用,而其他源文件的函数无法访问,这个时候就可以在变量声明前加上static关键字。
如下列在同一文件中的代码:
| 1 2 3 4 5 | static int a; int func1(){...} int func2(){...} | 
这个时候func1()和func2()两个函数都可以使用变量a,但是这两个函数的使用者如果不是在同一个源文件里的话是不可以访问到变量a的,变量a也不会和同一程序中的其他文件中相同的名字冲突。
用于函数声明
如果把函数声明为static类型,则该函数名除了对该函数声明所在的文件可见外,其他文件无法访问
用于声明函数内部变量
static一旦用于函数内部变量声明过后,被声明的变量不会随着所在函数的被调用和推出而存在和消失。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | #include<stdio.h> int test(){     static int b;     b++;     return b; } int main(){     test();     test();     printf("%d\n", test());     return 0; } | 
如上述代码的输出边是
| 1 | 3 | 
在类成员变量中使用
倘若在C++中类成员的声明中使用static关键字,那么无论有多少类的对象被创建,static声明的成员都会只有一个,不会被多次复制。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #include <iostream> using namespace std; class Box{     public:         static int number;         Box(){             number++;         } }; int Box::number = 0; int main(){     Box box1;     Box box2;     cout << Box::number << endl;     return 0; } | 
上述代码的输出是
| 1 | 2 | 
在类成员函数中使用
在类中声明函数的时候如果用了static关键字,那么即使没有创建对象也可以通过::直接访问。还需要注意的是,类当中的静态函数相应地只能访问静态变量,因此可以用一个静态函数来判断静态变量是否被成功创建
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; class Box{     public:         static int number;         Box(){             number++;         }         static int getnum(){             return number;         } }; int Box::number = 0; int main(){     Box box1;     Box box2;     cout <<         "get "<< Box::getnum() << endl;     return 0; } | 
上述代码的输出便是
| 1 | get 2 | 
References
http://stackoverflow.com/questions/943280/difference-between-static-in-c-and-static-in-c
http://www.tutorialspoint.com/cplusplus/cpp_static_members.htm