Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

Advantages of classes with only static methods in C++

Even though there are no static classes in C++, coming from a Java background I use to create a helper class like Util containing only static methods. Is this considered bad style or usual practice? One alternative I see is to use C functions (no class context at all). What other alternatives are there? What are there advantages and disadvantages and under which circumstances would I use any of these.

defining bunch of static methods in c++ suggests namespacing static functions as one alternative, though I fail to see what effects the static keyword without class context has.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to create a collection of utility functions without clobbering the global namespace, you should just create regular functions in their own namespace:

namespace utility {
    int helper1();
    void helper2();
};

You probably don't want to make them static functions either. Within the context of a non-member function (as opposed to a member function), the static keyword in C and C++ simply limits the scope of the function to the current source file (that is, it sort of makes the function private to the current file). It's usually only used to implement internal helper functions used by library code written in C, so that the resulting helper functions don't have symbols that are exposed to other programs. This is important for preventing clashes between names, since C doesn't have namespaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...