[英]How can I declare a variable so that it will hold its value and can be accessible from any class in C++?
My Projects contains multiple classes each has its own separate .h and .cpp file . 我的项目包含多个类,每个类都有自己的单独的.h和.cpp文件。
I want to declare a variable use so that I can access/modify its value from any of the classes . 我想声明一个变量use,以便可以从任何类中访问/修改其值。
You can add another translation unit to define a variable at namespace scope and make it accessible by providing a declaration: 您可以添加另一个转换单元以在命名空间范围内定义变量,并通过提供声明使其可访问:
var.h: var.h:
extern int a;
var.cpp: var.cpp:
#include "var.h"
int a = 15;
Now every translation unit in your program can #include "var.h"
and use a
. 现在,程序中的每个翻译单元可以
#include "var.h"
,并使用a
。
It may be sensible to a) give the variable a meaningful, unambiguous name, and b) place it in a named namespace. a)给变量赋予一个有意义的,明确的名称,然后b)将其放置在命名空间中可能是明智的。
You can use a public static variable in one of your classes or you can be naughty and declare a global variable outside of all your classes in one module and then use the extern keyword to reference it in other modules. 您可以在一个类中使用公共静态变量,也可以调皮并在一个模块中的所有类之外声明一个全局变量,然后在其他模块中使用extern关键字对其进行引用。
C++ is a hybrid OOP language: you don't have to use classes all the time. C ++是一种混合的OOP语言:您不必一直使用类。 If you do that, be ready to get flamed by self-righteous programmers and StackOverflow lurkers.
如果这样做,请准备好接受自以为是的程序员和StackOverflow潜伏者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.