【发布时间】:2011-02-16 02:12:18
【问题描述】:
我正在开发一个项目,其中一个头文件(比如 A.h)中声明了一个静态对象。我在另一个头文件中包含 A.h,我可以访问该对象及其函数和数据,就好像它是同一个对象一样。当我将 A.h 包含到 B.cpp 中并尝试使用相同的对象时,问题就开始了。该对象正常存在,但它不是同一个对象,即所有设置为其他值的成员现在都为 0。 我在这里遗漏了什么吗?
示例代码:
啊.h
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
【问题讨论】:
-
示例代码在这里会有所帮助。 'static' 可以在 C++ 中以多种方式使用,一种是显式创建您观察到的行为!
-
感谢 Daniel A. White,我得到了问题的答案。我把示例代码放进去,这样更容易理解。
标签: c++ static-variables