C++ 静态类不';在其他类之间不显示相同的值

C++ 静态类不';在其他类之间不显示相同的值,c++,C++,我希望我提供了足够的信息,并且我的标题正确 通常,我希望有一个类在我的应用程序中存储数据,我需要几个其他类来访问相同的数据。本质上是在多个类之间共享数据 简短代码如下: example.cpp(主应用程序) ObjecClass.cpp #include "ObjectClass.h" ObjectClass::ObjectClass() { a = 0; } 另一类 class AnotherClass { public: AnotherClass(); // Cons

我希望我提供了足够的信息,并且我的标题正确

通常,我希望有一个类在我的应用程序中存储数据,我需要几个其他类来访问相同的数据。本质上是在多个类之间共享数据

简短代码如下:

example.cpp(主应用程序)

ObjecClass.cpp

#include "ObjectClass.h"

ObjectClass::ObjectClass() {

    a = 0;

}
另一类

class AnotherClass {
public:
    AnotherClass(); // Constructor

    void PrintValue(); // Public function
    int value; // Public variable

};
另一个类.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";
}
#包括“AnotherClass.h”
#包括“ObjectClass.h”
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
另一个类::另一个类(){
值=MyObject.a;
}
void另一个类::PrintValue(){

coutstatic类实例本身就是一个静态变量。您期望发生的事情也是有意义的,但是,您的代码没有显示如何处理静态实例。事实上,如果两个
MyClassInstance
引用同一个对象,那么您甚至不需要静态声明


此外,静态变量在cpp文件中定义。如果在头文件中定义它,则cpp文件(编译单元)这包括它将定义一个单独的静态变量。因此,在主cpp文件中定义静态对象,并在头文件中使用
extern MyStaticClass
。然后链接器将使用链接到同一个变量。

你能发布一些真实的、可编译的代码重现你的问题吗?你正在寻找简短的C添加了可编译代码。这是一个非常简单的代码。它应该可以工作。上面已经添加了SCC。它非常简单,但似乎没有将静态对象视为包含相同的数据。您需要在一个cpp文件中定义静态变量,并在标题中使用
extern
。它的方式为每个cpp文件创建一个单独的对象编译单元。您是正确的,外部定义的变量是静态的,不需要这样声明。我将外部对象类MyObject;添加到我的AnotherClass.cpp中,并删除了Objectclass.h中的静态实例。然后,我在example.cpp(main)中添加了非静态对象类MyObject声明.一切正常。谢谢:)
class AnotherClass {
public:
    AnotherClass(); // Constructor

    void PrintValue(); // Public function
    int value; // Public variable

};
#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";
}