私は十分な情報を提供しており、これを正しく題名したことを願っています。staticクラスは他のクラスと同じ値を表示しません
一般に、アプリケーションにデータを格納するクラスが必要です。同じデータにアクセスするには、いくつかのクラスが必要です。基本的に複数のクラス間でデータを共有します。
短い/簡潔なコードは、以下:
example.cpp(メインアプリケーション)
// example.cpp : Defines the entry point for the console application.
//
#include "AnotherClass.h"
#include "ObjectClass.h"
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
//Prototype
static void do_example ();
int main()
{
do_example ();
}
static void do_example () {
MyObject.a = 5;
cout <<"MyObject.a value set in main application is "<<MyObject.a<<"\n";
AnotherClass m_AnotherClass;
m_AnotherClass.PrintValue();
}
ObjectClass.h
をObjecClass.cpp
#include "ObjectClass.h"
ObjectClass::ObjectClass() {
a = 0;
}
AnotherClass。 h
class AnotherClass {
public:
AnotherClass(); // Constructor
void PrintValue(); // Public function
int value; // Public variable
};
AnotherClass.cpp
#include "AnotherClass.h"
#include "ObjectClass.h"
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
AnotherClass::AnotherClass() {
value = MyObject.a;
}
void AnotherClass::PrintValue() {
cout <<"value in AnotherClass is "<<value<<"\n";
cout <<"it should be the same."<<"\n";
}
しかし、それはMyObjectにの新しいインスタンスであるかのように値が、0のデフォルト値です。しかし、静的なMyObjectから5の値を引き出す必要があります。
私には何が欠けていますか?
問題を再現する実際のコンパイル可能なコードを投稿してください。 – Mat
あなたは[シングルトンデザインパターン](http://stackoverflow.com/questions/1008019/c-singleton-design-pattern)を探しています –
短く/簡潔なコンパイル可能なコードが追加されました。それはとてもシンプルなコードです。それは動作するはずです。 – JeffS