静态类在其他类之间不显示相同的值

static Class doesn't show same values between other classes

本文关键字:显示 其他 之间 静态类      更新时间:2023-10-16

我希望我提供了足够的信息,并且我正确地命名了这个。

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

简短/简洁的代码如下:

示例.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

class ObjectClass {
public:
    ObjectClass(); // Constructor
    int a; // Public variable
} static MyObject;

ObjecClass.cpp

#include "ObjectClass.h"
ObjectClass::ObjectClass() {
    a = 0;
}

AnotherClass.h

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

但该值是默认值 0,就好像它是 MyObject 的新实例一样。但它应该从静态 MyObject 中提取值 5。

我错过了什么?

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

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