使用静态非成员函数中的静态 const 成员

Using a static const member from static non-member function

本文关键字:静态 成员 const 函数      更新时间:2023-10-16

>我在类中有一个私有的静态常量成员,在类实现中,我有静态函数尝试使用此常量,但它给了我错误。

//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
        //....
}

当我尝试使用 DoSomething 中的 X 并在static const int X = 1;‘const int A::X’ is private时,我会within this context.

我该如何解决这个问题?

您正在尝试从自由函数访问A的私有成员。这是不允许的。

你应该让它public,例如:

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

Jack 答案的另一种解决方案是使函数DoSomething()非静态的,并将其声明为 A 类的friend

//A.hpp
class A {
    static const int X = 1;
    // ....
    friend int DoSomething();
 };
//A.cpp
int DoSomething() {
    int n = A::X;
      //....
}