C++中的Helper方法及其可见性
Helper methods in C++ and their visibility
我有一个执行计算的函数,我希望能够在程序中的任何位置调用这个函数。我知道在Java中,我只需要在一个类中创建一个public static
方法。
到目前为止,在C++中,我已经为我的特定函数创建了一个namespace
。我遇到的问题是这个函数使用了它自己的辅助函数。我希望这些较低级别的功能是不可见的(即私有),但不确定如何做到这一点
到目前为止,我有这个代码:
namespace HelperCalc{
int factorial(int n){
return n <= 1 ? 1 : n*factorial(n-1);
}
double getProbability(int x, int y){
.....//do maths
.... = factorial(x);
}
}
例如,我希望能够调用getProbability()
,但我希望"隐藏"factorial()
。
使用匿名命名空间(在源文件中,而不是头文件中):
namespace {
int factorial(int n){
return n <= 1 ? 1 : n*factorial(n-1);
}
}
namespace HelperCalc{
double getProbability(int x, int y){
.....//do maths
.... = factorial(x);
}
}
分离要公开的函数的声明和定义。在实现文件中定义公共函数和辅助函数。
namespace.h
:
namespace X
{
void public_function();
}
namespace.cpp
:
// An anonymous namespace means functions defined within it
// are only available to other functions in the same source file.
namespace {
void helper_function()
{
// ...
}
}
namespace X
{
void public_function()
{
helper_function();
}
}
相关文章:
- 如何更改唯一指针向量的可见性
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 限制静态库中符号的可见性 (MSVC/Visual C++)
- 班级成员可见性C++
- 内联模板函数的可见性
- Clang 是否可以在使用可见性属性时生成导入库(不带 __declspec(dllexport))?
- std::mutex 的发布-获取可见性保证是否仅适用于关键部分?
- 符号可见性和 gcc 警告
- C++/libscreen 无法更新可见性
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- C++继承构造函数的可见性
- CRTP - 嵌套叶类类型的可见性
- C++模板 - 实例之间的通用操作和成员可见性
- 放松的订单和线程间可见性
- GCC 6.x警告有关Lambda可见性
- 在C++中声明可见性/访问权限的方法有何不同
- C++中的Helper方法及其可见性
- 如何在java中做什么在c++中是改变一个被覆盖的方法的可见性
- 如何在覆盖具有错误可见性的虚拟方法时得到警告
- 类方法的PostActive可见性