C++中如何使用无链接性的局部变量
至此,介绍了链接性分别为内部和外部、作用域为整个文件的变量。接下来介绍静态持续家族中的第三个成员–无链接性的局部变量。这种变量是这样创建的,将 stac 限定符用于在代码块中定义的变量。在代码块中使用 static 时,将导致局部变量的存储持续性为静态的。这意味着虽然该变量只在该代码块中可用,但它在该代码块不处于活动状态时仍然存在。因此在两次函数调用之间,静态局部变量的值将保持不变。静态变量适用于再生-可以用它们将瑞士银行的秘密账号传递到下一个要去的地方)。另外,如果初始化了静态局部变量,则程序只在启动时进行一次初始化。以后再调用函数时,将不会像自动变量那样再次被初始化。程序清单 9.9 说明了这几点。
// static.cpp -- using a static local variable
#include <iostream>
// constants
const int ArSize = 10;
// function prototype
void strcount(const char * str);
int main()
{
using namespace std;
char input[ArSize];
char next;
cout << "Enter a line:\n";
cin.get(input, ArSize);
while (cin)
{
cin.get(next);
while (next != '\n') // string didn't fit!
cin.get(next); // dispose of remainder
strcount(input);
cout << "Enter next line (empty line to quit):\n";
cin.get(input, ArSize);
}
cout << "Bye\n";
// code to keep window open for MSVC++
/*
cin.clear();
while (cin.get() != '\n')
continue;
cin.get();
*/
return 0;
}
void strcount(const char * str)
{
using namespace std;
static int total = 0; // static local variable
int count = 0; // automatic local variable
cout << "\"" << str <<"\" contains ";
while (*str++) // go to end of string
count++;
total += count;
cout << count << " characters\n";
cout << total << " characters total\n";
}
顺便说一句,该程序演示了一种处理行输入可能长于目标数组的方法。本书前面讲过,方法cin.get(inputArSize)将一直读取输入,直到到达行尾或读取了 ArSize-1个字符为止。它把换行符留在输入队列中。该程序使用 cin.get(next)读取行输入后的字符。如果 next是换行符,则说明 cimn.get(input,ArSize)读取了整行;否则说明行中还有字符没有被读取。随后,程序使用一个循环来丢弃余下的字符,不过读者可以修改代码,让下一轮输入读取行中余下的字符。参见【0voice C++】该程序还利用了这样一个事实,即试图使用 get(char *,int)读取空行将导致 cin 为 false。下面是该程序的输出:
Enter a line:
nice pants
"nice pant" contains 9characters
9 characters total
Enter nextline(emptyline to quit):
thanks
"thanks" contains 6characters
15 characters total
Enter next line(empty line to quit):
parting is such sweet sorrow
"parting i" contains 9 characters
24 characters total
Enter next line(emptyline to quit):ok
"ok"
contains 2 characters
26 characters total
Enter next line(empty line to quit):
Bye
注意,由于数组长度为10,因此程序从每行读取的字符数都不超过9个。另外还需要注意的是,每次函数被调用时,自动变量 count 都被重置为 0。然而,静态变量 total 只在程序运行时被设置为 0,以后在两次函数调用之间,其值将保持不变,因此能够记录读取的字符总数。