Qt C++创建一个所有类都可以访问的全局变量



是否可以创建一个全局可访问的变量,供程序中的所有类访问,如果我从一个类更改它的值,它也会为所有其他类更改?

如果是这样,我该如何实现?

每个人都在鹦鹉学舌地说"全局变量是邪恶的",但我说几乎所有东西都可以被使用或滥用。此外,如果全局变量本质上是坏的,那么它们一开始就根本不会被允许。在全局变量的情况下,很有可能意外滥用导致非常负面的后果,但如果你真的知道你在做什么,它们是 100% 好的:

// globals.h - for including globals
extern int globalInt; // note the "extern" part
// globals.cpp - implementing the globals
int globalInt = 667;

使用命名空间来避免命名冲突并保持范围更干净也可能是一个非常好的主意,除非您对命名约定特别细致,这是执行命名空间的旧"C"方法。

此外,特别是如果您使用多个线程,最好创建一个接口来访问封装的全局内容,该接口也将具有模块化锁,甚至在可能的情况下无锁(例如直接使用原子学(。

但全球化不一定是唯一的解决方案。根据你的实际需要,单例或静态类成员可能会做到这一点,同时保持它更整洁并避免使用邪恶的全局变量。

这样的变量必须在某处定义一次,然后在不同的编译单元中使用。但是,为了使用某些东西,你知道,你需要告诉编译器它存在(声明它(。extern关键字允许您声明其他位置存在某些内容

为了构建你的代码,你可以按照xkenshin14x(有点?(的建议去做:

全球.h

#pragma once
#include <string>
// Declaration
namespace global
{
extern int i;
extern float f;
extern ::std::string s;
}

全球.cpp

#include "global.h"
// Definition
namespace global
{
int i = 100;
float f = 20.0f;
::std::string s = "string";
}

主.cpp

#include "global.h"
int main(int argc, char *argv[])
{
std::cout << global::i << " " << global::f << " " << global::s;
return 0;
}

在这种情况下,最好使用命名空间,因为它可以让您避免全局变量固有的名称冲突。


或者,可以将所有全局内容封装在一个"全局"对象中。我引用了"global"这个词,因为这个对象确实是全局函数的静态的,所以从技术上讲,没有涉及全局变量:)

下面是一个仅标头实现:

全球.h

#pragma once
class Global
{
public:
int i = 100;
float f = 20.0f;
// and other "global" variable 
public:
Global() = default;
Global(const Global&) = delete;
Global(Global&&) = delete;
static Global& Instance()
{
static Global global;
return global;
}
};
namespace {
Global& global = Global::Instance();
}
// static Global& global = Global::Instance(); if you like

测试.h

#pragma once
#include "global.h"
struct Test 
{
void ChangeGlobal() {
global.i++;
}
};

主.cpp

#include <iostream>
#include "global.h"
#include "test.h"
int main()
{
Test t;
std::cout << global.i << " " << global.f << std::endl;
t.ChangeGlobal();
std::cout << global.i << " " << global.f << std::endl;
return 0;
}

这种方法至少有两个好处:

  1. 您实际上不会使用任何全局对象。
  2. Global类中,您可以在需要的地方添加带有互斥体的变量访问器。例如,void SetSomething(const Something& something) { ... }

如果您只在 UI 线程(用于 QApplication UI 应用程序(或主线程(用于 QCoreApplication 控制台应用程序(中使用此全局变量,则编码会很方便,您可以设计自定义数据结构。但是如果你在多线程环境中使用它,你应该需要互斥锁或原子来保护全局变量。

您可能知道,应避免使用全局变量。

但是你可以为全局变量创建一个头文件,并在你想使用它的每个地方 #include"globals.h"。然后,您可以正常使用每个变量。

相关内容

最新更新