我正在从事一个项目,其中一个头文件(比如 A.h)中声明了一个静态对象。我将 A.h 包含在另一个头文件中,我可以像访问同一个对象一样访问该对象及其函数和数据。当我将 A.h 包含到 B.cpp 中并尝试使用相同的对象时,问题就开始了。该对象存在,但它不是同一个对象,即所有设置为其他值的成员现在都为 0。 我在这里遗漏了什么吗?
示例代码:
啊啊
class foo {
int result;
// variables and methods
} static foo_obj;
B.h
#include "A.h"
// Do other things
foo_obj.manipulate_result(); // Uses methods of objects within B.h
// Do other things
foo_obj.showResult(); // This gives me a non-zero value
A.cpp
#include "A.h"
// Do other things
foo_obj.showResult();
// This outputs zero if called here even though
// foo_obj should be in the same state as in B.h
最佳答案
在您的实现文件中为 A.h
初始化静态变量 - 例如A.cpp
。同时将变量标记为 extern
。
关于c++ - 带有 Visual Studio 的 C++ 中的静态对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5011818/