Reputation: 3
#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. As I compile, it gives me an error. I am currently a beginner and still learning. Can someone explain this?
Upvotes: 0
Views: 55
Reputation: 118027
You can define the static
variable outside the class definition:
#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
:
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.
Output:
10
25
Upvotes: 3