微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

#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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。