Static(c++)

        When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).

A variable declared static in a function retains its state between calls to that function.

When modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.

Static data members of classes must be initialized at file scope.

In recursive code, a static object or variable is guaranteed to have the same state in different instances of a block of code.

The members of a union cannot be declared as static. An anonymous union declared globally must be explicitly declared static.

Objects and variables defined outside all blocks have static lifetime and external linkage by default. A global object or variable that is explicitly declared as static has internal linkage.

         

Examples

The following example shows how a variable declared static in a function retains its state between calls to that function.

#include <iostream.h>

void showstat( int curr ) {
static int nStatic; // Value of nStatic is retained
// between each function call
  nStatic += curr;
  cout << "nStatic is " << nStatic << endl;
}

void main() {
  for ( int i = 0; i < 5; i++ )
    showstat( i );
}

The following example shows the use of static in a class.

#include <iostream.h>

class CMyClass {
public:
  static int m_i;
};

int CMyClass::m_i = 0;

void main() {
  CMyClass a,b;
  cout << a.m_i << endl;
  cout << b.m_i << endl;
  a.m_i = 1;
  cout << a.m_i << endl;
  cout << b.m_i << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值