如何声明一个可以在整个程序中使用的全局变量 [英] How to declare a global variable that could be used in the entire program

查看:179
本文介绍了如何声明一个可以在整个程序中使用的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,我想在所有我的类中使用,而不需要将它传递给类的构造函数每次我想使用它。

I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I want use it. How would I accomplish this in C++?

谢谢。

推荐答案

global.h
extern int myVar;

global.cpp
#include "global.h"
int myVar = 0;  // initialize

class1.cpp
#include "global.h"
...

class2.cpp
#include "global.h"
...

class3.cpp
#include "global.h"
...

MyVar将作为全局变量在每个模块中被识别和使用。你不必有global.cpp。你可以在任何类.cpp中初始化myVar,但我认为这对于更大的程序更干净。

MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initialize myVar in any of the class .cpp's but I think this is cleaner for larger programs.

这篇关于如何声明一个可以在整个程序中使用的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆