如何将访问非全局类的全局函数全部放在一处?
我什至可能没有正确提出问题,但这就是我的情况。我有一个名称空间,我想将所有全局函数放入其中。我想在相应的 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会在自己的头文件中自行定义“全局函数”。如果您需要添加前向声明,请在那里进行。
在 .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.
正如 @Oli Charlesworth 所建议的,您可以在全局方法源文件中
#include
相应的类标头吗?As suggested by @Oli Charlesworth can you just
#include
the respective class headers in your global-methods source file?我无法将评论标记为答案,所以我会自己发布它 - 基本上 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.