租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

mfc怎么定义全局变量,mfc定义全局变量

发布时间:2023-09-21 07:44:05

mfc怎样定义全局变量

在 MFC 中,可使用以下两种方式定义全局变量:
1. 在 MFC 利用程序的 `CWinApp` 类派生类中定义全局变量。在 `CWinApp` 类派生类的头文件中声明并初始化全局变量,如:
```C++
class CMyApp : public CWinApp
{
public:
int m_nGlobalVar = 0; // 全局变量
// ...
};
```
然后在利用程序的源文件中可以通过以下方式访问全局变量:
```C++
CMyApp theApp; // 利用程序对象
// 通过利用程序对象访问全局变量
int nValue = theApp.m_nGlobalVar;
```
2. 使用 `extern` 关键字在需要访问全局变量的文件中声明全局变量。在某个源文件中定义全局变量,并在其他需要访问该全局变量的源文件中使用 `extern` 声明该全局变量,如:
```C++
// GlobalVars.cpp
int g_nGlobalVar = 0; // 全局变量定义
// OtherFile.cpp
extern int g_nGlobalVar; // 全局变量声明
// 在 OtherFile.cpp 中可以访问 g_nGlobalVar 全局变量
int nValue = g_nGlobalVar;
```
这样,在需要访问全局变量的源文件中使用 `extern` 声明全局变量,便可访问全局变量的值。