开发者

C++ communication between objects

开发者 https://www.devze.com 2023-04-08 16:40 出处:网络
I\'m sure this kind of question has been asked (and answered) before, so please link me to a previous discussion if so...

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 a开发者_开发知识库n 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号