仅在C ++中使用静态方法的类的优点 [英] 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.
建议将静态函数命名为一个替代方法,虽然我看不到什么影响 static code>关键字没有类上下文有。
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.
推荐答案
如果你想创建一个效用函数集合而不破坏全局命名空间,你应该自己创建常规函数命名空间:
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();
};
你可能不想让它们成为静态函数。
在函数(而不是方法)的上下文中,C和C ++中的static关键字简单地将函数的作用域限制为当前源文件(也就是说,它使函数私有当前文件)。它通常只用于实现由C语言编写的库代码使用的内部辅助函数,以便生成的辅助函数不具有暴露给其他程序的符号。这对于防止名称之间的冲突很重要,因为C没有命名空间。
You probably don't want to make them static functions either. Within the context of a function (as opposed to a method), 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.
这篇关于仅在C ++中使用静态方法的类的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!