静态存储持续性变量的3种链接性:
- 外部链接性,可在其他文件中访问(必须在代码块外面声明)
- 内部链接性,在当前文件中访问(必须在代码块外面声明,并使用static限定符)
- 无链接性,在当前函数或者代码块中访问(必须在代码块内声明,并使用static限定符)
静态持续变量与自动变量相比,存在的寿命更长。由于静态变量的数目在程序运行期间是不变的,因此程序不需要特殊装置来对其进行存储或管理。编译器将分配固定的内存块来存储所有的静态变量,这些变量在整个程序执行期间一种存在。
示例如下:
int a=10;//外部链接性的静态持续变量
static int b=20;//内部链接性
int fun()
{
static int c=30;//无链接性
return c;
}
#include <iostream>
using namespace std;
int a = 10; //外部链接性的静态持续变量
static int b = 20; //内部链接性
int fun()
{
static int c = 30; //无链接性
return c;
}
int main()
{
int d;
d = fun();
cout << a << "," << b << "," << d << endl;
system("pause");
return 0;
}
外部链接性:引用声明使用关键字extern,且不能进行初始化。引用声明的作用就是:如果要在多个文件中使用外部变量,只需在一个文件中包含该变量的含义,但在使用该变量的其他文件中,都必须使用关键字extern声明。
// file1.cpp
extern int cats = 10; //其中extern可以省略
int dogs = 20;
int fleas = 30;
...
// file2.cpp
extern int cats;
extern int dogs;
...
// file3.cpp
extern int cats;
extern int dogs;
extern int fleas;
内部连续性:
// file1.cpp
int cats = 10;
int dogs = 20;
// file2.cpp
int cats=15;
int dogs=25;
这种情况违反了但定义规则,会出现编译错误。如下做法则正确。
// file1.cpp
int cats = 10;
int dogs = 20;
// file2.cpp
static int cats=15;
static int dogs=25;
注:参考《C++ Primer第六版》