Advantages of classes with only static methods in C++(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.
这篇关于C++中只有静态方法的类的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中只有静态方法的类的优点


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01