Cross dependencies without forward declaring all used functions?

后端 未结 2 390
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题