C++ nested classes, access fathers variables [duplicate]

人盡茶涼 提交于 2019-12-05 11:02:06

Despite that you declared class B inside of A, classes A and B are still completely independent. The only difference is that now to refer to B, one must do A::B.

For B to access A's stuff, you should use composition or inheritance. For composition, give B a reference to an object of A, like so:

class B {
public:
  B(const A& aObj) : aRef(aObj) {
    cout << aRef.a << endl;
  }
private:
  const A& aRef;
};

For inheritance, something like this:

class B: public A { // or private, depending on your desires
  B() {
    cout << a << endl;
  }
}

The inner class is not related to the outer class in C++ as it is in Java. For an instance of A::B to access a member of an A object, it needs to have an instance of A somewhere, just as if B were not a nested class. Instances of A::B do not have any implicit instance of A; you can have many instances of A::B without any instances of A existing at all.

Pass an instance of A to test, and then use it to access the a member:

void test(A& a_instance)
{
  a_instance.a = 20;
}

Classes are types, types don't have data. Instances have data, but an instance of A does not (in your example) contain an instance of B, and the instances of B don't have any knowledge of any instance of A.

Choices

  • have B be a child of A instead of contained by A
  • have B's constructor take a ref to the A instance which created it (preferred)

Now, if the variable a is private this still won't help. You will either need an accessor a or a friend relation.

C++ nested classes are not like java nested classes, they do not belong to an instance of A but are static. So a doesn't exist at that point

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!