How can I avoid including class implementation files?

前端 未结 7 871
轮回少年
轮回少年 2020-11-29 11:45

Instead of doing

#include \"MyClass.cpp\"

I would like to do

#include \"MyClass.h\"

I\'ve read online tha

7条回答
  •  时光说笑
    2020-11-29 12:24

    One thing you will want to watch out for when including you class declarations from a .h/.hpp is make sure it only ever gets included once. If you don't do this you will get some possibly cryptic compiler errors that will drive you up the wall.

    To do this you need to tell the compiler, using a #define, to include the file only if the #define does not already exist.

    For example (MyClass.h):

    #ifndef MYCLASS_H
    #define MYCLASS_H
    class MyClass 
    {
    // Memebers and methods
    }
    #endif
    // End of file
    

    This will guarantee your class declaration only gets included once even if you have it included in many different .cpp files.

提交回复
热议问题