In C++, I want two classes to access each other

后端 未结 1 997
悲&欢浪女
悲&欢浪女 2021-01-17 06:54

I have two classes, class A and class B.

A.h -> A.cpp
B.h -> B.cpp

And then, I set B as a member in class A

1条回答
  •  礼貌的吻别
    2021-01-17 07:34

    Just use forward declaration. Like:

    A.h:

    #ifndef A_h
    #define A_h
    
    class B; // B forward-declaration
    
    class A // A definition
    {
    public:
        B * pb; // legal, we don't need B's definition to declare a pointer to B 
        B b;    // illegal! B is an incomplete type here
        void method();
    };
    
    #endif
    

    B.h:

    #ifndef B_h
    #define B_h
    
    #include "A.h" // including definition of A
    
    class B // definition of B
    {
    public:
        A * pa; // legal, pointer is always a pointer
        A a;    // legal too, since we've included A's *definition* already
        void method();
    };
    
    #endif
    

    A.cpp

    #inlude "A.h"
    #incude "B.h"
    
    A::method()
    {
        pb->method(); // we've included the definition of B already,
                      // and now we can access its members via the pointer.
    }
    

    B.cpp

    #inlude "A.h"
    #incude "B.h"
    
    B::method()
    {
        pa->method(); // we've included the definition of A already
        a.method();   // ...or like this, if we want B to own an instance of A,
                      // rather than just refer to it by a pointer.
    }
    

    Knowing that B is a class is enough for compiler to define pointer to B, whatever B is. Of course, both .cpp files should include A.h and B.h to be able to access class members.

    0 讨论(0)
提交回复
热议问题