Frage

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
War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top