【问题标题】:Using a static const member from static non-member function使用来自静态非成员函数的静态 const 成员
【发布时间】:2016-01-01 15:45:49
【问题描述】:

我在类中有一个私有静态 const 成员,在类实现中我有尝试使用此 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

我该如何解决这个问题?

【问题讨论】:

  • 请发布一些语法上有效的 C++ 代码。
  • 也许你应该把它改成public: static const int X = 1;
  • A.hpp 是不是很重要还是只是输入错误?

标签: c++ class static-members


【解决方案1】:

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

你应该把它设为public,例如:

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

【讨论】:

  • 但我不希望它公开......它仅供课堂内部使用
  • 你正试图从课堂外访问它,因为 DoSomething 不是课堂的一部分,所以你的要求没有得到满足。
  • 或者将DoSomething 声明为friendclass A
【解决方案2】:

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

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

    friend int DoSomething();
 };

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2021-12-03
    • 2011-05-31
    • 2011-10-22
    • 2016-05-20
    相关资源
    最近更新 更多