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