接下来介绍下无链接性的静态变量。
- #include <iostream>
- const int ArSize = 10;
- 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')
- cin.get(next);
- strcount(input);
- cout << "Enter next line (empty line to quit): \n";
- cin.get(input, ArSize);
- }
- cout << "Bye\n";
- return 0;
- }
- void strcount(const char * str)
- {
- using namespace std;
- static int total = 0; //静态存储,无链接性,作用域在函数中,但生命周期是整个文件,所以只经过一次初始化
- int count = 0; //每次执行函数都重新初始化这个变量
- cout << "\"" << str << "\" contains ";
- while(*str++)
- count++;
- total += count;
- cout << count << " characters\n";
- cout << total << " characters total \n";
- }
这个例子最好自己运行下,多动手就理解了。
接下来再简单说下const,在全局定义const就类似使用static说明符。如果要让一个常量的链接性为外部的,那么就用extern来覆盖原有的内部链接性。如 extern const int state = 10;
在C++中,针对函数有个单定义规则,对每个非内联函数,程序只能包含一个定义,对于链接性为外部的函数来说,意味着在多文件程序中,只有一个文件包含该函数定义,但使用该函数的每个文件都应包含函数原型。
下面简单说下布局new操作符,它可以指定要使用的位置,例如可以声明一个char型数组 buffer[100]然后使用布局new操作符来初始化,int *p = new (buffer)int[20];则说明了,p指向的数组放在了Buffer[]中,p的首地址就是buffer数组的首地址。
紧接着介绍下命名空间,命名空间不能位于代码块中。
- namespace Jill{
- int x;
- }
两者的不同是编译指令会使整个命名空间可用,但是using声明不会,他只是该用哪就用在哪,因为使用using编译指令的话,当出现了同名的局部变量则会覆盖命名空间里的变量。像上面的命名空间,using声明表示为 using Jill::x,using namespace Jill则是using编译指令。还有一种是没有命名的名称空间,如
- namespace
- {
- int y;
- }
可能听着晕乎乎的,还是上代码。答案我写在注释里了
- #include <iostream>
- using namespace std;
- void other();
- namespace n1
- {
- int x = 1;
- }
- namespace n2
- {
- int x = 2;
- }
- int main()
- {
- using namespace n1;
- cout << x << endl; // 1
- {
- int x = 4;
- cout << x << ", " << n1::x << ", " << n2::x << endl; // 4, 1, 2
- }
- using n2::x;
- cout << x << endl; // 2
- other();
- return 0;
- }
- void other()
- {
- using namespace n2;
- cout << x << endl; // 2
- {
- int x = 4;
- cout << x << ", " << n1::x << ", " << n2::x << endl; // 4, 1, 2
- }
- using n2::x;
- cout << x << endl; // 2
- }
