forward declarations

前端 未结 3 764
失恋的感觉
失恋的感觉 2020-12-20 07:42

Why do I need to use forward declarations for a class when I am already including the relevant header file? It has fixed my problem but confused me!

essentially clas

3条回答
  •  死守一世寂寞
    2020-12-20 08:23

    If you have a circular declaration dependence, you'll probably have something like this:

    • A.h defined class A and starts with #include "B.h"

    • B.h defined class B and starts with #include "A.h"

    Now, your header files will have include guards, so they're only included once. So in the context of B.h, there's only a single inclusion of A.h, so you'll get something that's effectively like this:

    class A { B * bp; };  // from `#include "A.h"`
    
    class B { A * ap; };
    

    Now you're stuck, because the first line is incorrect without having the declaration of B. You fix this by adding a forward declaration to A.h:

    // A.h
    #ifndef H_A
    #define H_A
    
    class B;
    class A { B * bp; };
    
    #endif
    

提交回复
热议问题