Cross dependencies without forward declaring all used functions?

后端 未结 2 368
不思量自难忘°
不思量自难忘° 2021-01-16 02:27

I have class A (in A.h) which depends on class B in (B.h) and vice versa. Forward declaring the used functions works, but this means I have to update everywhere where I forw

相关标签:
2条回答
  • 2021-01-16 02:41

    The best way is to have a forward declaration header:

    a.fwd.h

    #pragma once
    class A;
    

    a.h

    #pragma once
    #include "a.fwd.h"
    #include "b.fwd.h"
    class A
    {
        A(B*);
    };
    

    etc.

    This way, each class provides its own forward declarations - localised alongside the header where it belongs - checked for consistency with the real declarations and definitions by including the forward declaration header in the header, and the header in the implementation.

    0 讨论(0)
  • 2021-01-16 02:53

    If you only need to work with pointers or references to a class at the declaration level, you can do it like this:

    A.h

    class B; // forward class declaration
    
    class A {
        A(B &);
    };
    

    B.h

    class A;
    
    class B {
        B(A &);
    };
    

    B.cpp

    #include "B.h"
    #include "A.h" // now we get the full declaration of A
    
    B::B(A &a) {
        a.foo(5);
    }
    

    Mutual dependencies like this are tough to deal with but sometimes unavoidable.

    If A and B depend on the implementations of each other, then you've got a system design problem that you need to resolve before proceeding further.

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