问题
I have a class like this:
class A
{
protected:
int t = 10;
public:
void f()
{
struct B
{
void g()
{
print(t); //using t
}
};
B b;
b.g();
}
};
ERROR: a nonstatic member reference must be relative to a specific object
I see, members of class A is not visible in struct B (which is inside class A method). But how I may capture they, or make friends A and B? (If it's possible)
回答1:
Defining B
inside a method of A
does not make instances of A
contain a B
.
No matter where you define a class, you need an instance to call a non-static method. Making them friends would also not suffice, because you still need an A
instance, that you need to pass to B
somehow:
class A {
protected:
int t = 10;
public:
void f() {
struct B {
void g(A& a) {
int x = a.t;
}
};
B b;
b.g(*this);
}
};
回答2:
You need to pass A
object (this
here) to g
method to be able to access A
's data. E.g. via parameter:
void f()
{
struct B
{
void g(const A& a)
{
printf("%d", a.t); //using t
}
};
B b;
b.g(*this);
}
回答3:
An instance of the local class B
does not hold any aspect of an object of the class A
. In order to access member variables of A
in B::g()
, you'll have to pass a pointer/referece to an instance of A
to B::g()
.
class A
{
protected:
int t = 10;
public:
void f()
{
struct B
{
void g(A* a)
{
print(a->t);
}
};
B b;
b.g(this);
}
};
来源:https://stackoverflow.com/questions/58561649/how-to-use-member-of-a-class-in-a-local-class-in-a-method