qt-- qt全局变量和局部变量

文章介绍了两种全局变量的处理方法。第一种是头文件声明,源文件中赋值,需要使用extern关键字。第二种是在源文件中直接声明并赋值,其他文件使用时需extern。示例中涉及了QMutex的使用。

全局变量:方式1.在头文件中只做声明,源文件中赋值

方式2.在源文件中声明和赋值

全局变量方式1:在头文件中只做声明,用extern修饰,

在头文件中初始化赋值,或者在多个.cpp文件中初始化赋值,都会报错multiple definition 多重定义

只能在随便一个用到的.cpp中进行赋值,哪个文件需要使用该变量,只需include头文件就可以直接使用

声明部分:

#ifndef GENERAL_H
#define GENERAL_H
#include <QMutex>

extern int a;
extern QMutex * m_mutex;


#endif // GENERAL_H
定义赋值部分:
mywidget.cpp

#include "mywidget.h"
#include "ui_mywidget.h"
#include "general.h"
 int a=0;
 QMutex * m_mutex=new QMutex;

使用时,只需要包含头文件就可直接使用

#include "mythread.h"
#include "general.h"
.
.
m_mutex->lock();
.
m_mutex->unlock();

方式2:在源文件中声明和赋值

mywidget.cpp
#include "mywidget.h"
#include <QMutex>

QMutex * m_mutex=new QMutex;

在其他文件使用时,要用extern,不需要包含头文件

mythread。cpp
#include "mythread.h"

extern QMutex * m_mutex;

Qt中将局部变量变为全局变量的方法有很多种,以下是其中两种常见的方法: 1. 在头文件中声明变量 在需要使用全局变量的地方,可以在头文件中声明该全局变量,这样其他文件就可以通过包含该头文件来使用该全局变量。 例如,在头文件中声明一个全局变量: ```cpp // global.h #ifndef GLOBAL_H #define GLOBAL_H extern int globalVariable; #endif // GLOBAL_H ``` 在需要使用该全局变量的源文件中包含该头文件,并定义该全局变量: ```cpp // main.cpp #include "global.h" int globalVariable = 0; int main() { // 使用globalVariable return 0; } ``` 2. 使用单例模式 单例模式是一种常见的实现全局变量的方法,在Qt中也可以使用单例模式来实现全局变量。 例如,定义一个名为Global的单例类,在该类中定义全局变量: ```cpp // global.h #ifndef GLOBAL_H #define GLOBAL_H class Global { public: static Global& instance(); int globalVariable() const; void setGlobalVariable(int value); private: Global(); Global(const Global&); Global& operator=(const Global&); private: int m_globalVariable; }; #endif // GLOBAL_H ``` 在实现文件中实现该单例类: ```cpp // global.cpp #include "global.h" Global& Global::instance() { static Global global; return global; } int Global::globalVariable() const { return m_globalVariable; } void Global::setGlobalVariable(int value) { m_globalVariable = value; } Global::Global() : m_globalVariable(0) { } Global::Global(const Global&) { } Global& Global::operator=(const Global&) { return *this; } ``` 在需要使用该全局变量的地方,可以通过单例类的实例来获取设置该全局变量: ```cpp // main.cpp #include "global.h" int main() { Global& global = Global::instance(); global.setGlobalVariable(0); int variable = global.globalVariable(); // 使用variable return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值