C/C++ 语言的Static

在C语言中,static 具有的两重意义:

(1) 如果 static int foo; 这一句位于函数中,则 static 表示的是存储属性,表明 foo 是一个静态变量。放在静态存储区,只占一份空间。它的生存周期和程序一样长。

(2) 如果 static int foo;  这一句位于函数外面,则 foo 是一个全局变量,static 不再是表示存储性质,而是作为限制符来使用:用来限制全局变量 foo 的可见范围,将其作用域限制于所在的文件内,在其它文件中是不可见的。 
static void func();表示该函数只在本文件可见。

在C++中,类中的static成员表示所有对象共享存储区。静态成员函数只可以访问静态成员。静态成员初始化必须放在文件范围,即使是私有成员。静态成员函数调用可以用对象+成员函数,也可以用类+成员函数进行调用。

// Example of the static keyword
static int i;         // Variable accessible only from this file

static void func();   // Function accessible only from this file

int max_so_far( int curr )
{
   static int biggest;    // Variable whose value is retained
                          //    between each function call
   if( curr > biggest )
      biggest = curr;

   return biggest;
}

// C++ only

class SavingsAccount
{
public:
   static void setInterest( float newValue )  // Member function
      { currentRate = newValue; }             //    that accesses
                                              //    only static
                                              //    members
private:
   char name[30];
   float total;
   static float currentRate;    // One copy of this member is
                                //    shared among all instances
                                //    of SavingsAccount
};

// Static data members must be initialized at file scope, even
//    if private.
float SavingsAccount::currentRate = 0.00154;
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值