静态持续变量
静态持续变量3种链接性:外部链接性(可在其他文件中访问)、内部链接性(只能在当前文件中访问)、无链接性(只能在当前函数或代码中访问)。
要想创建链接性为外部或内部的静态持续变量,必须在代码块外面声明它,要创建没有链接性的静态持续变量,必须在代码块内声明它。
外部链接性
1.单定义规则
变量只能有一次定义,c++提供了两种变量声明,一种是定义声明(defining declaration)或简称为定义(definition),它会给变量分配储存空间;
另一种是引用声明(referencing declaration)或简称为声明(declaration),它不给变量分配储存空间,因为它引用已有的变量。
引用声明使用关键字extern
// file01.cpp
extern int cats = 20;
int dogs = 22;
int fleas;
…
//flie02.cpp
extern int cats;
extern int dogs;
…
内部链接性
将static 限定符用于作用域为整个文件的变量时,该变量的链接性将为内部的。 链接性为内部的变量只能在其所属的文件中使用;但常规外部变量都具有外部链接性,即可以在其他文件中使用。
//file01
int errors = 20;
…
//file02
int errors = 5;
void froo()
{
…
这种情况会失败
但是下面这种情况就可以
//file01
int errors = 20;
…
//file02
int errors = 5;
std::cout << errors;
//输出为5
无链接性
将static限定符用于在代码块中定义的变量。
这意味着虽然该变量只在该代码块中可用,但它在该代码块不处于活动状态时仍然存在,因此在两次函数调用之间,静态局部变量的值将保持不变。
例子:
#include<iostream>
const int ArSize = 10;
void strcout(const char* str);
int main()
{
using namespace std;
char input[ArSize];
cout << "Enter a line:";
while (cin.getline(input, ArSize))
{
strcout(input);
cout << "again:";
}
cout << "end";
return 0;
}
void strcout(const char* str)
{
using namespace std;
static int total = 0;
int count = 0;
cout << str;
while (*str++)
count++;
total += count;
cout << " contain: "<< count << " characters "
<<total << " total char " << endl;
}