简体   繁体   中英

C++ communication between objects

I'm sure this kind of question has been asked (and answered) before, so please link me to a previous discussion if so...

In C++, say I have an object of type ClassA which includes a private member variable object of type ClassB. How would I go about calling a reference to the ClassA object within ClassB?

I am using the Observer Design Pattern where the ClassA object is the 'subject' and an object within ClassB, say of type ClassC, is an 'observer' of the ClassA object. Therefore when initialising object ClassC within ClassB one of its parameters needs to be a reference to its 'subject' object.

Briefly:

struct A;

struct B : C {
  B(A &a) : c(a) { }

  C c;
};

struct A {
  A() : b(*this) { }

  private:
    B b;
};

B gets no special access to A just because it is a member. You must explicitly pass the reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM