考虑让一个变量由一个 .cpp
文件处理,而其他 .cpp
文件出于各种目的使用该变量的值。
与类一起使用时
// header.h
class c {
public:
static int f1();
static int f2();
private:
static int v;
};
// first.cpp
int c::v(0);
int c::f1() { return ++v; }
// second.cpp
int c::f2() { return ++v; }
// main.cpp
int main() {
cout << c::f1() << endl;
cout << c::f2() << endl;
return 0;
}
输出是:
1
2
在全局范围内使用时
// header.h
int f1();
int f2();
static int v = 0;
// first.cpp
int f1() { return ++v; }
// second.cpp
int f2() { return ++v; }
// main.cpp
int main() {
cout << f1() << endl;
cout << f2() << endl;
return 0;
}
输出是:
1
1
为什么当所述变量在一个类中时,输出是你所期望的,否则就不是? (我知道在第二部分中使用 extern
会得到想要的结果,问题是为什么 static
适用于类而不是全局范围? )
最佳答案
static
在C++中不止一个意思(语言设计者为了减少保留关键字的数量其实做了很多这件事)。
-
类中的
static
表示它是该类所有实例共享的变量。static
在编译单元中意味着它不能在不同的编译单元中寻址。在这种情况下,您在 header 中写入了static
;预处理器(通过``#include`s)将其插入可编译的源文件中。在包含此 header 的每个源文件中,它仅表示这是一个本地于此编译单元的变量。
关于c++ - 两个源文件之间的变量(类和全局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30967788/