Qt中extern全局变量的使用

参考网址:
https://blog.csdn.net/Soar_dream/article/details/101025153

https://blog.csdn.net/weixin_45571586/article/details/118109541?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_title~default-6.baidujsUnder6&spm=1001.2101.3001.4242

  1. 【声明】使用extern关键字,在头文件中类外部声明;
    例:在general.h中声明extern int num
extern int num;

注意,可重复声明,但是不能重复定义。

  1. 【定义】只能有一个文件定义一次
    例:在widget.h头文件中包含general.h,在widget.cpp的函数体外部定义 全局变量 num
int num =100;

注意只在一个文件中定义,别多重复定义,否则会报错multiple definition of ‘num’。

3.【使用】 在别的文件中使用到num这个全局变量时,直接包含general.h即可。
例:在t1.cpp中包含general.h,则在t1.cpp的函数体内可以直接使用num。

#include "t1.h"
#include "general.h"
void t1::test()
{
	qDebug()<<"t1::num = "<<num;
}

注意:使用extern 全局变量,会破坏封装性。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt,多文件全局变量使用可以通过以下几种方式实现: 1. 定义全局变量,在需要使用的文件使用extern关键字声明 定义一个全局变量,在一个文件使用,然后在其他文件使用extern关键字声明该变量即可使用: // global.h #ifndef GLOBAL_H #define GLOBAL_H extern int g_value; #endif // global.cpp #include "global.h" int g_value = 10; // main.cpp #include "global.h" #include <iostream> int main() { std::cout << g_value << std::endl; return 0; } 2. 使用单例模式 使用单例模式来创建一个全局变量,可以确保全局变量只被创建一次,同时可以方便地在多个文件使用该变量: // singleton.h #ifndef SINGLETON_H #define SINGLETON_H class Singleton { public: static Singleton& instance(); int value() const; void setValue(int newValue); private: Singleton(); Singleton(const Singleton&); Singleton& operator=(const Singleton&); int m_value; }; #endif // singleton.cpp #include "singleton.h" Singleton::Singleton() : m_value(0) { } Singleton& Singleton::instance() { static Singleton s; return s; } int Singleton::value() const { return m_value; } void Singleton::setValue(int newValue) { m_value = newValue; } // main.cpp #include "singleton.h" #include <iostream> int main() { std::cout << Singleton::instance().value() << std::endl; Singleton::instance().setValue(10); std::cout << Singleton::instance().value() << std::endl; return 0; } 3. 使用全局变量使用全局变量类可以方便地定义和管理全局变量,同时避免了使用全局变量时可能出现的一些问题: // globalvariable.h #ifndef GLOBALVARIABLE_H #define GLOBALVARIABLE_H template<typename T> class GlobalVariable { public: static T& instance(); private: GlobalVariable(); GlobalVariable(const GlobalVariable&); GlobalVariable& operator=(const GlobalVariable&); static T m_instance; }; template<typename T> T GlobalVariable<T>::m_instance; template<typename T> T& GlobalVariable<T>::instance() { return m_instance; } #endif // main.cpp #include "globalvariable.h" #include <iostream> int main() { GlobalVariable<int>::instance() = 10; std::cout << GlobalVariable<int>::instance() << std::endl; return 0; } 以上是Qt多文件全局变量使用方法,根据实际需要选择合适的方法即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值