拥有静态存储周期(static storage duration)的对象将会被一直保存到程序结束。
声明
存储类型说明符(static)用于声明对象拥有静态存储期(static storage duration)。
- 存储类型说明符(static)只可以用于对象,函数和匿名联合体。
- 块作用域中不能声明静态函数,也不能声明静态函数参数。
而这说明在其他作用域中声明静态函数和静态函数参数都是合法的,因此下面的程序是合法的。void func(static int tag){ cout<<tag<<endl; { static void nonStaticFunc(int x); // error! } };
#include<iostream> static void func(static int tag){ cout<<tag<<endl; }; int main(int argc, char *argv[]){ func(23); }
- 关键字 static 可以用于将类的数据成员或函数成员被声明为静态存储期,这些成员被称为类的静态成员(static member)。
- 类X的静态成员可以直接使用 qualified-id 表达式X::s来访问而不必使用点“.”或-箭头“->”来访问。 当使用点“.”或-箭头“->”来访问会先验证对象表达式(A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.)
#include<iostream> using namespace std; class process { public: static char* reschedule(){return "World!";}; }; process& g(){ process a; cout<<"Hello "; return a; }; int main(int argc, char *argv[]){ cout<<process::reschedule()<<endl; // OK: no object necessary "World!" cout<<g().reschedule()<<endl; // g() is called, "Hello World!" }
- 静态成员可以在其类中或其子类中直接使用qualified-id 表达式来访问。(In this case, the static member is referred to as if a qualified-id expression was used, with the nested-name-specifier of the qualified-id naming the class scope from which the static member is referenced.)
#include using namespace st
- 类X的静态成员可以直接使用 qualified-id 表达式X::s来访问而不必使用点“.”或-箭头“->”来访问。 当使用点“.”或-箭头“->”来访问会先验证对象表达式(A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.)