访问全局类对象的更好方法 C++
我有一个错误日志类,我在项目中的所有文件中都使用它。它使我能够进行调试并更好地了解我的代码正在做什么。我通过 Log errorLog 在 main.cpp 中全局声明它,然后相应地使用它。现在,我已经将文件拆分为多个文件,并且我总是通过使用“extern Log errorLog”在多个文件中使用记录器,并且效果很好。
现在,我正在尝试找出一种方法来做到这一点,而无需简单地在顶部添加外部人员。一位朋友提到了有关单例模式的事情。谁能解释一下这个概念?有没有人有不同的可行的概念。
谢谢!
I have an error log class that I use throughout all the files in my project. It allows me to debug and have a greater understanding of what my code is doing. I declare it globally in main.cpp by saying Log errorLog and then use it accordingly. Now, I have been splitting files into multiple files and the way I have always gotten away with using my logger in multiple files by using "extern Log errorLog" and it works great.
Now, I am trying to figure out a way I can do this without simply including an extern at the top. A friend mentioned something about a singleton pattern. Can anyone explain this concept? Does anyone have a different concept that will work.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请尽快使用
extern
并忘记单例。假装你从未听说过它们。 :) 另请参阅此和这个答案。另一种可能性是将记录器传递到需要它的每个函数和类中,即使使用 extern,全局仍然是全局,并且 全局变量被认为是不好的。
Stay with the
extern
and forget about singletons, asap please. Pretend you never heard of them. :) Also see this and this answer.Another possibility is to pass your logger into every function and class that needs it, as even with
extern
, a global is still a global, and global variables are considered bad.