简体   繁体   中英

How to make large numbers of existing functions available in the scope of a class?

I need to make a large (100's of source files) project into a library, removing dozens of global variables by putting them all into a class object.

The problem is the thousand or so functions that now need to be members of this class so they have access to the object variables.

Otehr than adding MyClass:: to every single function definition in the source files, is there a way to cheat and indicate that all the functions in a particular source file should be part of the MyClass scope?

Add all the globals to a namespace .

// MyGlobals.h
namespace MyGlobals
{
  extern int g_i;
  extern double g_d;
  extern A g_A;
}

Whatever files you want to access, do:

using namespace MyGlobals;

inside the header file. In this ( using namespace ) way you can indicate that all the variables should be accessible without using scope resolution :: for that file. (ie you can simply access g_i instead of MyGlobals::g_i inside that file).

Also note that, you have to define all the global variables inside a .cpp file:

// MyGlobals.cpp
#include "MyGlobals.h"

int MyGlobals::g_i;
double MyGlobals::g_d;
A MyGlobals::g_A;

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