简体   繁体   English

我如何声明一个变量,使其保留其值并可以从C ++中的任何类访问?

[英]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.

相关问题 我如何在 C++ 中声明 Class - how can i declare a Class in C++ 如何声明带有void *指针的C ++原型,以便它可以采用任何指针类型? - How do I declare a C++ prototype with a void * pointer so that it can take any pointer type? 我如何在c ++中稍后转发类的声明并使用其成员函数? - How can I forward declare a class and use its member funcions later in c++? 如何在 c++ 中声明一个相同的 class 但具有不同模板参数的新变量? - How can I declare a new variable of the same class but with different template parameters in c++? 我可以在C ++类中将成员变量声明为const吗? - Can i declare member variable as const in class of c++?if yes,how? 在 C++ 中,如何保存抽象类的列表? - In C++, how can I hold a list of an abstract class? 如何在C ++中声明不可变类(Java示例) - how can I declare an immutable class in C++ (Java Example) 我可以使用C ++中的函数来初始化类成员变量吗? 如果可以,该怎么办? - Can I initialize a class member variable using function in C++? If so how to do it? 如何使用c ++中另一个类的值? - How can I use a value from another class in c++? 在 C++ 中,我可以创建一个线程并将其保存为类成员变量,以便它可以在析构函数中自动加入吗? - In C++, can I create a thread and save it as a class member variable so it can be joined automatically in the destructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM