gpt4 book ai didi

c++ - 用于数据存储的静态类

转载 作者:行者123 更新时间:2023-11-30 02:02:28 25 4
gpt4 key购买 nike

我是 C++ 语言的新手。我将它与 Qt 一起使用来创建一个跨平台的用户界面。用户界面将使用相同的数据显示不同的图形和绘图。所以我想将我的数据存储在一个类 (Data_Class) 中,所有其他类都可以访问该类。在数据类中,我使用私有(private)静态变量和公共(public)静态方法(获取/设置)。

我不清楚的是如何从其他类访问数据类。换句话说,我把数据值写到Class_A(到Data_Class)之后,如何得到Class_B(从Data_Class)的数据值。

最佳答案

假设这是一个面向语法的问题:

class Data_Class {
public:
static int a;
static int GetA() const { return a; }
}

A类中:

Data_Class::a;
Data_Class::GetA();

不要忘记添加Data_Class static members definitions , 例如到 dataclass.cpp:

static int Data_Class::a = 0;

否则你会得到一个undefined reference linker error .


您也可以考虑使用 singleton pattern (根据评论,单例是个坏主意,你应该尽可能避免)作为Aubin suggested它将负责添加新的静态成员定义:

class Data_Class {
private:
Data_Class(); // Prevents multiple instances

int a;
int b;

public:
// Will initialize instance if needed
static Data_Class &GetInstance(){
static Data_Class instance;
return instance;
}


int GetA() const {return a;}
};

用法:

Data_Class::GetInstance().GetA()

或者选择更复杂但更灵活的 Dependency injection这是根据维基:

Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time. This can be used, for example, as a simple way to load plugins dynamically or to choose mock objects in test environments vs. real objects in production environments. This software design pattern injects the dependent element (object or value etc) to the destination automatically by knowing the requirement of the destination.

关于c++ - 用于数据存储的静态类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com