What are the most common uses of static class functions in C++?
I am learning today a开发者_如何转开发bout static class functions in C++ and I can't really understand what are they good for? Does anyone have some good examples where they can be applied successfully?
Thanks, Boda Cydo.
Static member functions of a class are just ordinary (non-member) functions. You do know what ordinary functions are good for, do you? So, static member functions are good for the same things for the same reasons.
It is just that sometimes an ordinary function has a tight relationship with the class, so it makes sense to declare it as a static member of the class, instead of declaring it as a completely independent standalone function. It helps you to express the fact that the function has that tight relationship with the class. Besides, this gives that function full access rights to the innards of the class - to its private and protected members.
The latter actually makes it possible to implement some useful programming idioms and patterns using static member function. Do a search, for example, for "static constructor" idiom.
Static classes are similar to namespaces, but they offer protection (protected and private), and can be turned into templates (yes, bare functions can too, but they have restrictions that sometimes make a wrapping class template easier or even necessary).
Static member functions can be used to perform non-trivial initialization on static, constant data members. For instance, you have may a static, constant container you use in some class. A static member function can be used to create an instance of the container that gets returned and copied into the static, constant data member.
Think "global". A non-static function, as you are learning operates on a single object whereas a static function is shared by all objects of a class - so ... what do all of those object have in common?
It varies depending on your class, but think about "summary information". Think about the data. Think what is common across all objects of the class. Maybe each has a running total, specific to itself, but you also want a global total? Think along those lines...
精彩评论