繁体   English   中英

如何在内部 class 中访问 class 的 static 成员?

[英]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();
}

所以这是代码。 我需要给 static integer 赋值。 当我编译时,它给了我一个错误。 我目前是初学者,仍在学习。 有人可以解释一下吗?

您可以在 class 定义之外定义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 ,因为它们不返回任何内容。

Output:

10
25

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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