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.
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?
如果您不希望覆盖sumElapsed,则可以,但是,将sumElapsed作为静态变量封装在classA中似乎更有意义。
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 !
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 (eg in C).
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.