Qt 中使用全局变量

这篇博客介绍了在Qt 4.7.4环境下如何声明和定义全局变量。首先,在全局头文件'global.h'中使用extern关键字声明变量,然后在'main.cpp'的main函数之前进行实际的变量定义。
摘要由CSDN通过智能技术生成

环境:Qt 4.7.4


1. 在全局头文件 "global.h" 声明 extern 变量

#ifndef GLOBAL_H
#define GLOBAL_H

extern int ItemFlag;

#endif // GLOBAL_H

2. 在 "main.cpp" main{} 函数体之前定义上述变量

#include <QtGui/QApplication>
#include "mainwindow.h"
#include "global.h"

int ItemFlag = 0;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}


3. 如果类 A 要使用上面的全局变量,在 A.cpp 文件中包含 global.h,即可使用



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值