Header files inclusion / Forward declaration

后端 未结 5 923
北海茫月
北海茫月 2020-12-24 03:39

In my C++ project when do I have to use inclusion (#include \"myclass.h\") of header files? And when do I have to use forward declaration of the class (cl

5条回答
  •  误落风尘
    2020-12-24 04:08

    As a beginner, you should always #include header files when you need to use the types or functions they contain - do not try to "optimise" your build by forward declaring things - this is hardly ever necessary, even on large projects, provided the project is well architected.

    The only time you absolutely need a forward declaration is in situations like this:

    struct A {
       void f( B b );
    };
    
    struct B {
       void f( A a );
    };
    

    where each struct (or class) refers to the type of the other. In this case, you need a forward declaration of B to resolve the issue:

    struct B;   // forward declaration
    
    struct A {
       void f( B b );
    };
    
    struct B {
       void f( A a );
    };
    

提交回复
热议问题