C++中只有静态方法的类的优点

2022-01-05 00:00:00 static c++

即使 C++ 中没有静态类,来自 Java 背景,我用来创建一个像 Util 这样只包含静态方法的辅助类.这被认为是糟糕的风格还是通常的做法?我看到的一种替代方法是使用 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.

在 C++ 中定义一堆静态方法 建议对静态函数进行命名空间作为一种替代方法,虽然我没有看到没有类上下文的 static 关键字有什么影响.

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 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.

相关文章