C++中的Helper方法及其可见性

Helper methods in C++ and their visibility

本文关键字:可见性 方法 中的 Helper C++      更新时间:2023-10-16

我有一个执行计算的函数,我希望能够在程序中的任何位置调用这个函数。我知道在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();
    }
}