开发者

Static Objects in C++ with Visual Studio

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


Initialize the static variable in your implementation file for A.h - e.g. A.cpp. Also mark the variable as extern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜