在 C++ 源文件中隐藏变量的可见性

Hiding visibility of variables in a c++ source file

我正在使用 cpp 文件来初始化一些数据

// foo.cpp

#include "foo.h"

int val = 5;

& 使用 header 与项目中的其他文件共享。

// foo.h

extern int val;

inline int get() {
    return val;
}

但我不希望在项目的其他文件中访问变量 val。我想通过 get() 函数访问该值。有什么办法可以实现吗?

我试过另一种方法...

// foo.h

class foo {

private:

    static int val;

public:

    static int get() {
        return val;
    }

    static void set();
}

&...

// foo.cpp

void foo::set() {
    val = 5;
}

但它也不起作用。获取链接器错误:未解析的外部符号"private: static int foo::val".

在foo.cpp中添加:-

 int foo::val;

放入.cpp文件

int foo:val = 5;

为其提供所需的 space。

您需要 class 成员或自由变量?如果你想要自由变量,只需从头文件中删除变量声明,删除 get() 的定义(保留声明)并在 .cpp 文件中实现 get()