[英]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.
我需要给 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:您可以在 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();
}
Or define it inline
:或者
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.注意:我将您的成员函数更改为
void
,因为它们不返回任何内容。
Output: Output:
10
25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.