c++ header files including each other mutually

后端 未结 6 1457
失恋的感觉
失恋的感觉 2020-12-07 17:29

I have two classes both defined in separate header files. Each file has a field that is type of other class. Now I included in header of each file the header of other file,

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 18:21

    You shouldn't include the header files inside the other ones, just include the header files in your source files.

    In the headers you can use a forward declaration:

    // In Class1.h
    class Class2;
    
    // In class2.h
    class Class1;
    

    Also you can protect against a file being included twice using the preprocessor:

    // Class1.h
    #ifndef __CLASS_1_H
    #define __CLASS_1_H
    
    // content
    
    #endif
    

提交回复
热议问题