Hi i need help with this little example.
I am unable to use _test
from the nested class
class random
{
public:
int _test;
class nestedClass
{
public:
void notify() override {
_test = 123;
}
} _nestedClass;
};
CodePudding user response:
You can use/pass a pointer to the outer class named random
to achieve what you want as follows:
void notify(random* p)
{
p->_test = 123;
}
This is because a nested class can access a non-static member of the enclosing class through a pointer to the enclosing class.
You can also pass arguments as:
void notify(random* p, int i)
{
p->_test = i;
}
CodePudding user response:
You can't access the non-static member of random without a instance of random. You need to tell your nestedClass
which _test
it want to access. There may be many instances of random
out there, and therefor, many _test
s.
I think what you want is:
class random
{
public:
int _test;
class nestedClass
{
random& outer_;
public:
nestedClass(random& outer): outer_(outer) {
}
void notify() {
outer_._test = 123;
}
} _nestedClass;
random(): _nestedClass(*this) {
}
};