考虑具有一个由一个.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/

    10-11 22:47
    查看更多