全局自创建对象
我正在制作一个 VC++ 2008 windows 项目,我希望有一个我实例化的对象,其存在的目的是为了全球范围内的所有强烈目的。该对象应该是一个计时器,用于监视程序运行了多长时间,并且需要可由其他对象访问以生成日志文件。我知道我可以将本机和 sudo-native(字符串)成员标记为 extern 以使它们可访问,但是如何使对象全局存在于其他对象中。 我是否将对象定义放在需要知道其存在的对象的类之前(确保首先加载该类),还是必须在 main 中放置一个允许访问该对象的方法?
I am making a VC++ 2008 windows project, and I want to have an object that I instantiate exist for all intense, and purposes globally. this object shall be a timer to monitor how long the program has been running, and needs to be accessible by other objects for the purpose of log file generation. I know that I can mark native, and sudo-native (string) members as extern to make them reachable, but how do I get an object to exist globally to other objects.
Do I put the object definition before the class of the object that needs to know of its existence (insuring to load the class first), or must I put a method in my main that allows access to the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需创建一个包含所需方法的类,然后声明该类的实例为全局
在您想要使用该类的所有模块中包含该类的标头以及
外部声明告诉模块该定义在其他地方。也许你
有一些全部包含的通用标头。
全局定义应该是 main() 所在的位置
,或者如果您更喜欢使用指针在堆上分配它,则在 main 开始处分配
并在末尾删除并将指针设置为全局。
也就是说,全局声明通常不好,您应该声明
main() 中的 MyClass ,然后将指向它的指针传递给所有函数/类
你用。我就是这么做的。那么你不需要 extern 语句,只需
包含标头 MyClass.h
全局实例的一个问题是您几乎无法控制它们何时出现
创建/销毁。
Just create a class with the methods you need, then declare an instance of the class global
include the header of the class in all your modules where you want to use it plus have
an extern declaration telling the modules that the definition is elsewhere. Maybe you
have some common header that all include.
The global definition should be where the main() is
or if you prefer allocate it on the heap by using a pointer, then allocate at start of main
and delete at end and just have the pointer as global.
that said, it is normally not good to have global declarations instead you should declare
the MyClass in the main() and then pass a pointer to it to all functions/classes that
you use. that is how i would do it. Then you don't need the extern statement and just
include the header MyClass.h
one problem with global instances is that you have little or no control of when they are
created/destroyed.
您所描述的通常是使用单例完成的。
下面是如何编写一个示例:单例:应该如何使用
这是另一个:
任何人都可以为我提供C++ 中的 Singleton 示例?
另请注意:单例有什么不好?
What you describe is often done using a singleton.
Here's an example on how to write one: Singleton: How should it be used
Here's another one:
Can any one provide me a sample of Singleton in c++?
Also note: What is so bad about singletons?