简体   繁体   中英

How do I access a static member of class inside an inner class?

#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();
}

So this is the code. I need to give a value to the static integer. As I compile, it gives me an error. I am currently a beginner and still learning. Can someone explain this?

You can define the static variable outside the class definition:

#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();
}

Or define it inline :

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

Note: I changed your member functions to void since they don't return anything.

Output:

10
25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM