Should every C or C++ file have an associated header file?

后端 未结 15 2494
情话喂你
情话喂你 2021-02-04 06:30

Should every .C or .cpp file should have a header (.h) file for it?

Suppose there are following C files :

  1. Main.C

  2. Func1.C

  3. <
15条回答
  •  故里飘歌
    2021-02-04 07:26

    I like putting interfaces into header files and implementation in cpp files. I don't like writing C++ where I need to add member variables and prototypes to the header and then the method again in the C++. I prefer something like:

    module.h

    struct IModuleInterface : public IUnknown
    {
        virtual void SomeMethod () = 0;
    }
    

    module.cpp

    class ModuleImpl : public IModuleInterface,
                       public CObject // a common object to do the reference
                                                  // counting stuff for IUnknown (so we
                                                  // can stick this object in a smart 
                                                  // pointer).
    {
        ModuleImpl () : m_MemberVariable (0)
        {
        }
    
        int m_MemberVariable;
    
        void SomeInternalMethod ()
        {
            // some internal code that doesn't need to be in the interface
        }
    
        void SomeMethod ()
        {
            // implementation for the method in the interface
        }
    
        // whatever else we need
    };
    

    I find this is a really clean way of separating implementation and interface.

提交回复
热议问题