如何将访问非全局类的全局函数全部放在一处?

发布于 2024-10-16 18:01:00 字数 387 浏览 4 评论 0原文

我什至可能没有正确提出问题,但这就是我的情况。我有一个名称空间,我想将所有全局函数放入其中。我想在相应的 .cpp 文件中定义它们。其中许多函数访问非全局类的实例,这些类本身可能是也可能不是命名空间的成员。我可以前向声明这些类,但是当我尝试调用类方法时,我当然仍然会遇到链接器错误。一种(看起来很糟糕的)解决方案是在定义相应的类之后定义每个全局变量,但这会将不同的函数放在不同的文件中,我想不惜一切代价避免这种情况,这样做似乎严重错误。

我还能做什么?我想我在这里遇到了一个概念问题,什么样的设计策略可以帮助解决这个问题?我是否必须将它们设为相应类的静态成员?我不喜欢这个 b/c 我的类有很长的名称,但我的命名空间名称很短......所以只需使用 typedef ?但从概念上讲,这些是全局函数,所以我想保持这种方式......感谢您的考虑。

I might not even be posing the question correctly, but here's my situation. I have a namespace into which I want to put all of my global functions. I want to define them all in the corresponding .cpp file. Many of these functions access instances of non-global classes, which may or may not be themselves members of the namespace. I can forward-declare the classes, but I will of course still get linker errors when I try to invoke the class methods. One (terrible-seeming) solution is to define each of these globals after the corresponding classes have been defined, but this puts different functions in different files and I want to avoid this at all costs, doing this seems deeply wrong.

What else can I do? I guess I'm having a conceptual issue here, what sort of design strategies might help resolve this? Do I have to make them static members of the corresponding classes? I don't like this b/c my classes have long names but my namespace name is short... so just use a typedef? But conceptually these are global functions, so I would like to keep them that way... Thanks for your consideration.

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

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

发布评论

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

评论(3

多情出卖 2024-10-23 18:01:00

我会在自己的头文件中自行定义“全局函数”。如果您需要添加前向声明,请在那里进行。

在 .cpp 文件中,只需根据需要包含其他“非全局”类和函数的标头。这将使公共 API 保持“干净”(头文件),同时让您在这些函数的实际代码中正常开发。

I would define the "global functions" in their own header file, on their own. If you need to add forward declarations, do so there.

In the .cpp file, just include the headers for the other "non-global" classes and functions as needed. This will keep the public API "clean" (the header file), while letting you develop normally in the actual code for these functions.

梦与时光遇 2024-10-23 18:01:00

正如 @Oli Charlesworth 所建议的,您可以在全局方法源文件中 #include 相应的类标头吗?

As suggested by @Oli Charlesworth can you just #include the respective class headers in your global-methods source file?

韶华倾负 2024-10-23 18:01:00

我无法将评论标记为答案,所以我会自己发布它 - 基本上 Oli Charnesworth 是对的,重构是解决方案。有一个特定的类导致了我的循环依赖问题,我只是重新做了一些事情,以便它不再依赖于“全局”信息,而是“全局”信息#included它。

I can't mark a comment as the answer, so I'll just post it myself--basically Oli Charnesworth was right, refactoring was the solution. There was a particular class which was causing my circular dependencies problem, and I just redid things so that it no longer depended on the 'global' info, rather the 'global' info #included it.

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