控制符号可见性的标准方法

lve*_*lla 1 c++ c++14

在C++中使用C和plain函数,我可以使用static关键字阻止函数的符号输出:

static int foo(int a, int b) { /* ...  */ }
Run Code Online (Sandbox Code Playgroud)

但在一个类中,定义一个函数static具有完全不同的含义.有没有办法确保编译器我的整个类只能在模块中使用,而且不需要导出它的任何方法的符号?

Chr*_*ckl 7

使用匿名命名空间.

namespace
{
    class C
    {
        C() {}
        void f() {}
    };

    void f();
}

class ExportedClass
{
    ExportedClass() {}
    void f() {}
};

void exportedFunction() {}
Run Code Online (Sandbox Code Playgroud)

如您所见,您也应该为正常功能执行此操作.static不鼓励使用此方法.


Wal*_*ter 5

您可以使用匿名命名空间.例如,

// file foo.cc
namespace {
    int symbol1 = 0;
    struct auxiliary { /* ... */ } symbol2;
}

void foo(int x)
{
  // uses symbol1 and symbol2
}
Run Code Online (Sandbox Code Playgroud)

何时symbol1symbol2不"可见".