0

私は、ヘッダー ファイルの 1 つに静的オブジェクトが宣言されているプロジェクトに取り組んでいます (Ah など)。Ah を別のヘッダー ファイルにインクルードすると、同じオブジェクトであるかのようにオブジェクトとその関数とデータにアクセスできます。Ah を B.cpp にインクルードし、同じオブジェクトを使用しようとすると、問題が発生します。オブジェクトは問題なく存在しますが、同じオブジェクトではありません。つまり、他の値に設定されていたすべてのメンバーが 0 になっています。ここで何か不足していますか?

コード例:

ああ

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
4

1 に答える 1

3

A.hたとえば、実装ファイルで静的変数を初期化しますA.cpp。また、変数を としてマークしますextern

于 2011-02-16T02:14:39.457 に答える