static in C/C++
最近经常碰到static,之前也使用过,但都是一知半解,所以下决心做个整理总结,搞搞灵清它到底用哪些作用。
一.static in C
1.默认初始化为0:
如果不显式地对静态变量进行初始化,它们将被初始化为0。
static变量存放在Global/Static(全局区/静态区)。在静态数据区,内存中所有的字节默认值都是0x00,所以在程序一开始时static声明的变量会被默认初始化为0。
2.static声明的变量会一直保持其值(局部静态对象)
static变量存放在Global/Static(全局区/静态区)。程序一开始,对其进行唯一一次初始化。被函数调用后,static变量不会消失,计算机会一直记录其值,其生命周期是贯穿函数调用及之后的时间。
1 #include <stdio.h> 2 void funcion(); 3 4 int main() 5 { 6 for(int count = 1; count <= 3; count++) { 7 printf("第%d次调用:",count); 8 funcion(); 9 } //for循环中的count内存被释放 10 return 0; 11 } 12 13 void funcion() 14 { 15 int temp = 10; 16 static int count = 10;//只在函数第一次调用时执行,后续函数调用此变量的初始值为上次调用后的值,每次调用后存储空间不释放 17 printf("temp = %d static count = %d ",temp--, count--); 18 }
static count每次调用,其值减1,而temp每次都重新开始都为10。而主函数for循环中的count是在栈区的,作用域只在主函数的for循环中,当循环结束是存储空间自动释放。
3.具有内部链接的静态变量(static variable with internal linkage)
普通的外部变量可以被程序的任一文件所包含的函数使用,而具有内部链接的静态变量只可以被与它在同一个文件中的函数使用。
1 //举个例子 2 文件1:a.c 3 int money = 10; 4 static wife = 1; 5 int main() 6 { 7 money++; 8 printf("wife = %d ",wife); 9 } 10 void function() 11 { 12 money--; 13 printf("wife = %d ",wife); 14 } 15 文件2:b.c 16 int main() 17 { 18 extern int money; 19 money--; 20 printf("money = %d ",money); 21 return 0; 22 }
a.c中main函数,function函数皆可调用money和wife。b.c用外部声明extern money,是可以输出money = 9的。但是不能extern int wife,因为在a.c 中wife 加了static,其只允许在a.c中使用。(就像好兄弟money是可以共享的,但是wife不行!)
在多文件构成的程序中,如需共享一个外部变量,除了一个声明(定义声明)外,其他所有声明都要加extern;而如果不想被共享的变量,那就在声明时用static,表明该变量具有内部链接。
二.static in C++
1.静态数据成员
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 5 class Account 6 { 7 public: 8 static int sumAccount; //声明静态数据成员 9 void calculate() { 10 amount += amount * interestRate; 11 } 12 static double rate() { 13 return interestRate; 14 } 15 static double rate2(double interestRate2 = interestRate) {//使用静态成员作为默认实参。 16 return interestRate2; 17 } 18 // [Error] invalid use of non-static data member 'Account::amount'普通数据成员值不能作为默认实参 19 // static double showAmount(double Amount = amount) { 20 // return Amount; 21 // } 22 static void rate(double); 23 private: 24 string owner; 25 double amount; 26 static double interestRate; //声明静态数据成员 27 static double initRate(); 28 }; 29 double Account::interestRate = 0.30;//定义并初始化静态数据成员 30 int Account::sumAccount = 10000; //定义并初始化静态数据成员 31 32 int main() 33 { 34 Account ac1; 35 Account *ac2 = &ac1; 36 Account &ac3 = ac1; 37 cout << ac1.sumAccount << endl; 38 cout << ac2->sumAccount << endl; 39 cout << ac3.sumAccount << endl; 40 cout << Account::sumAccount << endl; 41 return 0; 42 }