简体   繁体   中英

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 .
I want to declare a variable use so that I can access/modify its value from any of the classes .

You can add another translation unit to define a variable at namespace scope and make it accessible by providing a declaration:

var.h:

extern int a;

var.cpp:

#include "var.h"

int a = 15;

Now every translation unit in your program can #include "var.h" and use a .

It may be sensible to a) give the variable a meaningful, unambiguous name, and b) place it in a named namespace.

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.

C++ is a hybrid OOP language: you don't have to use classes all the time. If you do that, be ready to get flamed by self-righteous programmers and StackOverflow lurkers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM