[英]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.