使用来自静态非成员函数的静态常量成员

Using a static const member from static non-member function

我在 class 中有一个私有静态 const 成员,在 class 实现中我有静态函数试图使用这个 const,但它给我错误。

//A.hpp
class A {
    static const int X = 1;     //<<problem here
    // ....
}

我有

//A.cpp
static int DoSomething();
// ....
static int DoSomething {
    int n = A::X;           //<<problem here
        //....
}

当我尝试在 static const int X = 1;.

中使用 DoSomething‘const int A::X’ is private 中的 X 时,我得到 within this context

我该如何解决?

您正试图通过自由函数访问 A 的私有成员。这是不允许的。

你应该做到public,例如:

class A {
public:
  static const int X = 1;
}

Jack 答案的另一种解决方案是使函数 DoSomething() non-static 并将其声明为 friend of class A:

//A.hpp
class A {
    static const int X = 1;
    // ....

    friend int DoSomething();
 };

//A.cpp
int DoSomething() {
    int n = A::X;
      //....
}