静态类在其他类之间不显示相同的值
static Class doesn't show same values between other classes
我希望我提供了足够的信息,并且我正确地命名了这个。
通常,我希望有一个在应用程序中存储数据的类,并且我需要其他几个类来访问相同的数据。 本质上是在多个类之间共享数据。
简短/简洁的代码如下:
示例.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
。然后,链接器会将用途链接到同一变量。
相关文章:
- 当我尝试将范围值存储为 8 位的固定宽度整数时,它向我显示一些其他值 [ASCII]
- QSqlRelationalTable如何在具有外键的列中显示其他表的值
- 错误 LNK1104:错误消息中显示的路径未在其他依赖项中定义
- 通过屏蔽 UI 中的所有其他控件,在 UWP 应用 (c++) 中的现有 MainPage.xaml 顶部显示进度条
- 是否有类型特征显示一种类型是否可能包含其他类型的值
- 如何将OpenCV的输出显示或流式传输到HTML页面或其他一些客户端应用程序
- 使用 main() 以外的其他函数显示类的对象,但在 main() 中调用;
- 显示未显示QT其他类的文本框
- 显示主窗体 Qt C++ 中的其他窗体
- 无法在Windows对话框上显示其他Unicode Eastern Lanuage
- Doxygen 不显示如何从其他类调用记录的成员函数(包括构造函数)
- 如何只插入数字和字母应该显示消息或其他内容
- 如果不是,如何停止显示来自其他的消息
- 如何在Qt中显示其他应用程序的输出视频
- 静态类在其他类之间不显示相同的值
- 当键入指定单词作为第一个字母时显示输出,并忽略后面的其他单词
- 我的函数显示垃圾,其他时候它显示干净的结果
- 如何在程序的内存中搜索图像/png/jpeg/任何其他类型并显示它
- 用于c++ 11的Vim语法高亮显示不会混淆其他高亮显示.例如,类/命名空间作用域
- 读取文本文件c++(不能显示其他行)