QT-C++-再说全局对象的调用

1. 定义和声明全局对象

首先,在一个源文件中定义全局对象,并在一个头文件中声明它。

头文件 globals.h  源文件 globals.cpp

 

globals.h

#ifndef GLOBALS_H
#define GLOBALS_H

// 假设有一个类 ConfigLoad
class ConfigLoad {
public:
    void setConfig(int value);
    int getConfig() const;
private:
    int configValue;
};

// 声明全局对象
extern ConfigLoad g_config_load;

#endif // GLOBALS_H





globals.cpp
#include "globals.h"

// 定义全局对象
ConfigLoad g_config_load;





2. 定义 ConfigLoad 类
 

 头文件 globals.h  源文件 globals.cpp




 

// configload.h

#ifndef CONFIGLOAD_H
#define CONFIGLOAD_H

class ConfigLoad {
public:
    void setConfig(int value);
    int getConfig() const;
private:
    int configValue;
};

#endif // CONFIGLOAD_H




// configload.cpp

#include "configload.h"

void ConfigLoad::setConfig(int value) {
    configValue = value;
}

int ConfigLoad::getConfig() const {
    return configValue;
}






3.在类中使用全局对象
 

类1 中的修改

Class1 中,你可以修改 g_config_load 对象的状态:



 

// class1.h

#ifndef CLASS1_H
#define CLASS1_H

#include "globals.h"

class Class1 {
public:
    void updateConfig(int newValue);
};

#endif // CLASS1_H



// class1.cpp

#include "class1.h"

void Class1::updateConfig(int newValue) {
    g_config_load.setConfig(newValue);
}





 

类2 中的读取

Class2 中,你可以读取 g_config_load 对象的状态:

// class2.h

#ifndef CLASS2_H
#define CLASS2_H

#include "globals.h"

class Class2 {
public:
    void printConfig() const;
};

#endif // CLASS2_H



// class2.cpp

#include "class2.h"
#include <iostream>

void Class2::printConfig() const {
    std::cout << "Current config value: " << g_config_load.getConfig() << std::endl;
}








 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值