簡體   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