对象从诞生到结束的这段时间,即对象的生存期。在生存期间,对象将保持其状态(即数据成员的值),变量也将保持它的值不变,直到它们被更新为止。
ios
做用范围 | 用法及特色 |
---|---|
命名空间做用域 | 所声明的对象都具备静态生存期,无需再加static进行声明 |
函数内部局部做用域 | 声明静态对象时,需加关键字static 如:static int i; 局部做用域中的静态变量,当一个函数返回时,下次再调用时, 该变量还会保持上回的值,即便发生递归调用,也不会为该变量 创建新的副本,该变量会在每次调用间共享 |
2.定义时未指定初值的基本类型静态生存期变量,会被赋予0值进行初始化,
而对于动态生存期变量,不指定初值意味着初值不肯定,即随机值
函数
1.可观察不一样变量的生存期和可见性
测试
#include <iostream> int i = 1;//i为全局变量,具备静态生存期 using namespace std; void Other() { //a、b为局部静态变量,具备全局的寿命,只在第一次调用函数时初始化 static int a = 2; static int b; //c为局部变量,具备动态生存期,每次调用函数时,都会被从新初始化 int c = 10; a += 2; i += 32; c += 5; cout << "---Other---" << endl; cout << "i= " << i << endl; cout << "a= " << a << endl; cout << "b= " << b << endl; cout << "c= " << c << endl; } int main() { //a为静态局部变量,具备全局寿命 static int a; //b、c是局部变量,具备动态生存期 int b =-10; int c = 0; cout << "---MAIN---" << endl; cout << "i= " << i << endl; cout << "a= " << a << endl; cout << "b= " << b << endl; cout << "c= " << c << endl; c += 8; Other(); cout << "---MAIN---" << endl; cout << "i= " << i << endl; cout << "a= " << a << endl; cout << "b= " << b << endl; cout << "c= " << c << endl; i += 10; Other(); return 0; }
运行结果:
spa
2.具备静态和动态生存期对象的时钟
(1)clock的头文件
code
//声明一个包含时钟类的命名空间 #ifndef clock_H #define clock_H namespace myspace { class Clock{ public: Clock(int newh,int newm,int news); Clock() { hour=0; mintue=0; second=0; } void settime(int newh,int newm,int news); void showtime(); private: int hour,mintue,second; }; } #endif
(2)头文件内函数的实现
对象
#include<iostream> #include"clock.h" using namespace std; using namespace myspace; void Clock::settime(int newh, int newm, int news) { hour = newh; mintue = newm; second = news; } void Clock::showtime() { cout << hour << ":" << mintue << ":" << second << endl; }
(3)main函数测试
blog
#include<iostream> #include "clock.h" using namespace std; using namespace myspace;//使用自定义的命名空间,具备静态生存期 int main() { Clock c;//myspace里面的成员类 cout << "The First Time" << endl; c.showtime(); c.settime(2, 20, 30); cout << "The Second Time" << endl; c.showtime(); system("pause"); }
运行结果:
递归