在类中声明静态变量是否有意义?对象是静态的函数

发布于 2025-01-03 15:06:00 字数 285 浏览 0 评论 0原文

假设我的班级假设我有

static classA myObject;

void classA::update(int elapsed)
{
  static int sumElapsed = 0;
  sumElapsed+= elapsed;

}

似乎我的问题有点难以理解。但如果我们说 myObject 是 classA 的单例。除了可以访问的范围之外,本地 static int sumElapsed 和 classA 的私有成员 int sumElapsed 之间是否有区别?

Lets say my class lets say I have

static classA myObject;

void classA::update(int elapsed)
{
  static int sumElapsed = 0;
  sumElapsed+= elapsed;

}

It seems that my questions is kind of hard to understand. But if we say that myObject is a singleton of classA. Is there a difference between the local static int sumElapsed and a private member int sumElapsed of the classA, other than the scope in which they can get accessed.

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

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

发布评论

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

评论(5

吃兔兔 2025-01-10 15:06:00

当然。例如在单例模式中。静态方法也会返回对静态变量的引用(或指针)。


有关示例,请参见此处: c++ Meyers 单例未定义参考

顺便说一句,如果您是感兴趣:单例真的那么糟糕吗?

Sure. For example in the singleton pattern. There a reference (or pointer) to the static variable is also returned from a static method.


For an example see here: c++ Meyers singleton undefined reference

By the way, if you are interested: Are Singletons really that bad?

镜花水月 2025-01-10 15:06:00

如果您不希望 sumElapsed 被覆盖,那么可以,但是将 sumElapsed 作为静态变量封装在 classA 中似乎更有意义。

If you don't want sumElapsed to be overwritten then yes, but it does seem like it would make more sense to have sumElapsed ecapsulated within classA as a static variable.

假扮的天使 2025-01-10 15:06:00

实际上,当您需要在类模板中使用某种静态成员时,首先并没有真正好的替代方案。另外,如果成员不是微不足道的,您可能希望首先将它们放入函数中,以便对初始化顺序进行一定程度的控制。

一般来说,请注意,无论将静态成员放入类还是函数中,它仍然有效地实现了单例反模式

Effectively, when you need some sort of a static member in a class template there aren't really good alternatives in the first place. Also, if the members aren't trivial you probably want to put them into a function in the first place to have some level of control over the order of initialization.

In general, be aware that whether you put a static member into a class or into a function, it is still effectively implementing the Singleton anti-pattern!

演出会有结束 2025-01-10 15:06:00

当然。如果 sumElapsed 不是静态的,则每次调用该函数时它都会被覆盖;事实如此,也不会如此。 classA::update 本身是静态的这一事实是无关紧要的;只需考虑它是否是一个全局函数(例如在 C 中)。

Of course. If sumElapsed isn't static, it will get overwritten every time the function is called; as it is, it won't be. The fact that classA::update is itself static is irrelevant; just consider if it was a global function (e.g. in C).

感情旳空白 2025-01-10 15:06:00

您应该使用静态类来保存与特定对象无关的方法。话虽如此,使用静态类仅保存不能由对象实例化且不应被覆盖的静态成员。

You should use a static class to hold methods that are not associated with a particular object. That being said, use a static class to hold only static members that cannot be instantiated by objects, and shouldn't be overwritten.

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