我正在开发一个项目,其中一个头文件(比如 Ah)中声明了一个静态对象。我在另一个头文件中包含 Ah,我可以访问该对象及其函数和数据,就好像它是同一个对象一样。当我将 Ah 包含到 B.cpp 中并尝试使用相同的对象时,问题就开始了。该对象正常存在,但它不是同一个对象,即所有设置为其他值的成员现在都为 0。我在这里遗漏了什么吗?
示例代码:
啊
class foo {
int result;
// variables and methods
} static foo_obj;
溴化氢
#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