How can I avoid including class implementation files?

前端 未结 7 867
轮回少年
轮回少年 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

    You needn't include .c or .cpp files - the compiler will compile them regardless whether they're #included in other files or not. However, the code in the .c/.cpp files is useless if the other files are unaware of the classes/methods/functions/global vars/whatever that's contained in them. And that's where headers come into play. In the headers, you only put declarations, such as this one:

    //myfile.hpp
    class MyClass {
        public:
            MyClass (void);
            void myMethod (void);
            static int myStaticVar;
        private:
            int myPrivateVar;
    };
    

    Now, all .c/.cpp files that will #include "myfile.hpp" will be able to create instances of MyClass, operate on myStaticVar and call MyClass::myMethod(), even though there's no actual implementation here! See?

    The implementation (the actual code) goes into myfile.cpp, where you tell the compiler what all your stuff does:

    //myfile.cpp
    int MyClass::myStaticVar = 0;
    
    MyClass::MyClass (void) {
        myPrivateVar = 0;
    }
    
    void MyClass::myMethod (void) {
        myPrivateVar++;
    }
    

    You never include this file anywhere, it's absolutely not necessary.

    A tip: create a main.hpp (or main.h, if you prefer - makes no difference) file and put all the #includes there. Each .c/.cpp file will then only need to have have this line: #include "main.hpp". This is enough to have access to all classes, methods etc. you declared in your entire project :).

提交回复
热议问题