如何使大量现有函数在类的范围内可用?

发布于 2024-11-19 16:00:47 字数 227 浏览 2 评论 0原文

我需要将一个大型(数百个源文件)项目放入一个库中,通过将数十个全局变量全部放入一个类对象中来删除它们。

问题是现在有大约一千个函数需要成为这个类的成员,以便它们能够访问对象变量。

除了将 MyClass:: 添加到源文件中的每个函数定义之外,是否有一种方法可以欺骗并指示特定源文件中的所有函数都应该是 MyClass< 的一部分/代码> 范围?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过度放纵 2024-11-26 16:00:47

将所有全局变量添加到命名空间

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

无论您想访问什么文件,请

using namespace MyGlobals;

在头文件中执行以下操作:通过这种(使用命名空间)方式,您可以指示所有变量都应该可以访问,而无需对该文件使用作用域解析 ::。 (即您可以简单地访问该文件内的 g_i 而不是 MyGlobals::g_i)。

另请注意,您必须在 .cpp 文件中定义所有全局变量:

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

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

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. (i.e. 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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文