Is is a good practice to put the definition of C++ classes into the header file?

前端 未结 5 1742
暖寄归人
暖寄归人 2020-12-02 09:01

When we design classes in Java, Vala, or C# we put the definition and declaration in the same source file. But in C++ it is traditionally preferred to separate the definitio

5条回答
  •  佛祖请我去吃肉
    2020-12-02 09:18

    Two particular problems with putting everything in the header:

    1. Compile times will be increased, sometimes greatly. C++ compile times are long enough that that's not something you want.

    2. If you have circular dependencies in the implementation, keeping everything in headers is difficult to impossible. eg:

      header1.h

      struct C1
      {
        void f();
        void g();
      };
      

      header2.h

      struct C2
      {
        void f();
        void g();
      };
      

      impl1.cpp

      #include "header1.h"
      #include "header2.h"
      
      void C1::f()
      {
        C2 c2;
        c2.f();
      }
      

      impl2.cpp

      #include "header2.h"
      #include "header1.h"
      
      void C2::g()
      {
        C1 c1;
        c1.g();
      }
      

提交回复
热议问题