Is there a standard #include convention for C++?

前端 未结 8 1797
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 16:49

This is a rather basic question, but it\'s one that\'s bugged me for awhile.

My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.

I f

相关标签:
8条回答
  • 2021-01-01 17:44

    I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.

    Bar.h:

    class Foo;
    
    class Bar
    {
        Foo * m_foo;
    };
    

    Bar.cpp:

    #include "Foo.h"
    #include "Bar.h"
    
    0 讨论(0)
  • 2021-01-01 17:48

    Use only the minimum amount of includes needed. Useless including slows down compiling.

    Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:

    class BogoFactory;
    

    edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:

    a.h
    #include "b.h"
    
    b.h
    #include "c.h"
    

    If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.

    0 讨论(0)
提交回复
热议问题