静态成员函数生命期

块级别的局部静态对象其作用域局部于块,但其生命周期与全局对象相
同 ,只是在第一次遇见时分配空间并初始化。具体情况见实例:

#include <iostream>
#include <stdio.h>
using namespace std;

int count = 0 ;

class myclass
{
    char cc;
public:
    myclass(char ch)
    {
 ++count;
 cc = ch;
 cout << "costructor:count = "  << count << ",ch = " << ch << endl;

    }
   
    ~myclass()
    {
 --count;
 cout << "destructor:count = " << count << ",cc = " << getcc() << endl;
    }
   
    char getcc()
    {
 return cc;
    }
};

myclass globalG('G');

int main()
{
    myclass autoA('A');
    for(int i = 1;i <= 2;i++)
    {

  cout << "-----begin block----" << endl;
 myclass autoB('B');
 static myclass staticS('S');
 cout << "-----end block-----" << endl;
    }
    cout << "----end main----" << endl;
    return 0;
}

 

 

结果:costructor:count = 1,ch = G
costructor:count = 2,ch = A
-----begin block----
costructor:count = 3,ch = B
costructor:count = 4,ch = S
-----end block-----
destructor:count = 3,cc = B
-----begin block----
costructor:count = 4,ch = B
-----end block-----
destructor:count = 3,cc = B
----end main----
destructor:count = 2,cc = A
destructor:count = 1,cc = S
destructor:count = 0,cc = G

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值