全局变量的使用【C++/Qt】

本文介绍了在C++中如何通过两种不同的方式管理全局变量:一种是使用extern关键字定义全局变量并在其他文件中引用;另一种是利用static关键字在类中声明静态成员变量。推荐使用后者以提高代码的封装性和模块化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转:https://blog.youkuaiyun.com/caoshangpa/article/details/51104022

一、使用extern关键字

cglobal.h


 
  1. #ifndef CGLOBAL_H  
  2. #define CGLOBAL_H  
  3. extern int testValue;  
  4. #endif // CGLOBAL_H  

cglobal.cpp


 
  1. #include "cglobal.h"  
  2.   
  3. int testValue=1;  

调用方式


 
  1. #include "cglobal.h"  
  2. #include <QDebug>  
  3.   
  4. qDebug()<<testValue;  
  5. testValue=2;  
  6. qDebug()<<testValue;  

二、使用static关键字

cglobal.h


 
  1. #ifndef CGLOBAL_H  
  2. #define CGLOBAL_H  
  3.   
  4. class CGlobal  
  5. {  
  6. public:  
  7.     CGlobal();  
  8.     ~CGlobal();  
  9.   
  10. public:  
  11.     static int testValue;  
  12. };  
  13.   
  14. #endif // CGLOBAL_H  

cglobal.cpp


 
  1. #include "cglobal.h"  
  2. CGlobal::CGlobal()  
  3. {  
  4. }  
  5. CGlobal::~CGlobal()  
  6. {  
  7. }  
  8. int CGlobal::testValue=1;  

调用方式


 
  1. #include "cglobal.h"  
  2. #include <QDebug>  
  3.   
  4. qDebug()<<CGlobal::testValue;  
  5. CGlobal::testValue=2;  
  6. qDebug()<<CGlobal::testValue;  

建议使用第二种方式

转载于:https://www.cnblogs.com/judes/p/9188150.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值