Two classes that refer to each other

后端 未结 3 512
我在风中等你
我在风中等你 2020-12-09 16:33

I\'m new to C++, so this question may be basic:

I have two classes that need to refer to each other. Each is in its own header file, and #include\'s the other\'s he

相关标签:
3条回答
  • 2020-12-09 16:48

    You need a forward declaration.

    0 讨论(0)
  • 2020-12-09 16:55

    Forward declaration is the way to go.

    If you are using pointers\reference in class header then Forward declaration at both sides would work for you.

    If you are creating the object as a class member then you must include header itself. ( Forward declaration won't work as compiler needs class definition for knowing the size).

    Refer C++ FAQ for solving such senario:

    If you are creating the Window as member then include the Window header in App but at the same time Window shouldn't include the App's header. Use the combination of pointer to App and the forward declaration there.

    0 讨论(0)
  • 2020-12-09 17:09

    You can use forward declarations in the header files to get around the circular dependencies as long as you don't have implementation dependencies in the headers. In Window.h, add this line:

    class App;
    

    In App.h, add this line:

    class Window;
    

    Add these lines before the class definitions.

    Then in the source files, you include the headers for the actual class definitions.

    If your class definitions reference members of the other class (for example, in inlines), then they need to be moved to the source file (no longer inline).

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