如何在内部类中访问类的静态成员?

问题描述

#include <iostream>
using namespace std;
    
class outer {
  public :
    int a=10;   //non-static
    static int peek;   //static
    int fun()
    {
      i.show();
      cout<<i.x;
    }
  
      
    class inner {
      public :
        int x=25;
        int show()
        {
          cout<<peek;   
        }
    };
    inner i; 
    int outer::inner::peek=10; //here is the problem 
};  
    
int main()
{
  outer r;
  r.fun();
}

这是代码。我需要给静态整数一个值。 当我编译时,它给了我一个错误。我目前是初学者,仍在学习。 有人能解释一下吗?

解决方法

您可以在类定义之外定义 static 变量:

#include <iostream>
 
class outer {
public:
    int a = 10;        //non-static
    static int peek;   //static
   
    void fun() {
        i.show();
        std::cout << i.x << '\n';
    }
   
    class inner {
    public:
        int x = 25;
        void show() {
            std::cout << peek << '\n';
        }
    };

    inner i; 
};

int outer::peek = 10;  // <----------- here
 
int main() {
    outer r;
    r.fun();
}

或者定义它inline

class outer {
public:
    int a = 10;                   //non-static
    static inline int peek = 10;  //static inline
    // ...

注意:我将您的成员函数更改为 void,因为它们不返回任何内容。

输出:

10
25