根据维基百科:
http://en.wikipedia.org/wiki/External_variable
外部变量也可以在函数内声明.
在函数中声明外部变量的目的是什么?它也必须是静态的吗?
在命名空间范围内声明外部变量的唯一区别是:
extern int x;
void foo() {
cout << x;
}
Run Code Online (Sandbox Code Playgroud)
并在函数范围内声明它:
void foo() {
extern int x;
cout << x;
}
Run Code Online (Sandbox Code Playgroud)
是在后一种情况下,仅x在函数内部可见。
你们所做的只是进一步收紧声明的范围extern。
这是使用命名空间的类似示例:
在命名空间范围内:
#include <string>
using std::string;
void foo() {
string str1;
}
string str2; // OK
Run Code Online (Sandbox Code Playgroud)
在函数范围内:
#include <string>
void foo() {
using std::string;
string str1;
}
string str2; // Error - `using` not performed at this scope
Run Code Online (Sandbox Code Playgroud)