C++ 中的静态对象与视觉工作室
我正在开发一个项目,其中一个头文件中声明了一个静态对象(比如 Ah)。我将 Ah 包含在另一个头文件中,并且可以访问该对象及其函数和数据,就好像它是同一个对象一样。当我将 Ah 包含到 B.cpp 并尝试使用相同的对象时,问题就开始了。该对象正常存在,但它不是同一个对象,即所有设置为其他值的成员现在都是 0。 我在这里错过了什么吗?
示例代码:
Ah
class foo {
int result;
// variables and methods
} static foo_obj;
Bh
#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
I'm working on a project where there's a static object declared in one of the header files (say A.h). I include A.h in another header file, and I can access the object and it's functions and data as if it were the same object. The problem starts when I include A.h into B.cpp and try and use the same object. The object exists alright, but it's not the same object, i.e all the members that were set to some other value are now 0.
Am I missing something here?
Example Code:
A.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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在实现文件中初始化
Ah
的静态变量 - 例如A.cpp
。还将变量标记为extern
。Initialize the static variable in your implementation file for
A.h
- e.g.A.cpp
. Also mark the variable asextern
.