C++ 静态存储周期(static storage duration)

拥有静态存储周期(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
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值