C++ #include guards

后端 未结 8 895
鱼传尺愫
鱼传尺愫 2020-11-22 13:24

SOLVED

What really helped me was that I could #include headers in the .cpp file with out causing the redefined error.


I\'m new to C++ but I have some p

8条回答
  •  生来不讨喜
    2020-11-22 13:40

    The goal of a header guard is to avoid including the same file many times. But the header guard that is currently used in C ++ can be improved. The current guard is:

    #ifndef AAA_H
    #define AAA_H
    
    class AAA
    { /* ... */ };
    
    #endif
    

    My new guard proposal is:

    #ifndef AAA_H
    #define AAA_H
    
    class AAA
    { /* ... */ };
    
    #else
    class AAA;  // Forward declaration
    #endif
    

    This resolves the annoying problem that occurs when the AAA class needs the BBB class declaration, while the BBB class needs the AAA class declaration, typically because there are crossed pointers from one class to the other:

    // File AAA.h
    #ifndef AAA_H
    #define AAA_H
    
    #include "BBB.h"
    
    class AAA
    { 
      BBB *bbb;
    /* ... */ 
    };
    
    #else
    class AAA;  // Forward declaration
    #endif
    
    //+++++++++++++++++++++++++++++++++++++++
    
    // File BBB.h
    #ifndef BBB_H
    #define BBB_H
    
    #include "AAA.h"
    
    class BBB
    { 
      AAA *aaa;
    /* ... */ 
    };
    
    #else
    class BBB;  // Forward declaration
    #endif
    

    I would love for this to be included in the IDEs that automatically generate code from templates.

提交回复
热议问题