开发者

including .h files

开发者 https://www.devze.com 2022-12-30 10:39 出处:网络
Suppose I have two .h files: A.h and B.h. Moreover, A.h includes B.h itself: B.h - defines class B. class B {

Suppose I have two .h files: A.h and B.h. Moreover, A.h includes B.h itself:

B.h - defines class B.

class B {
  ...
};

A.h - defines class A, which uses class B.

#include B.h

class A {
  void SomeFunction(const B& b);
};

Now, I have some .cpp file, that uses both A and B classes (B class maybe used not on开发者_Go百科ly in A::SomeFunction(B))

What are the pluses to include both A.h and B.h (instead of only A.h) from the perspective of design-patterns and coding style.


Including both "A.h" and "B.h" makes the dependencies completely clear. There is no reason why "A.h" could not have forward-declared class B, and so including both headers prevents your ".cpp" file from breaking should the transitive include be changed to a forward declaration. In general, it is not a good idea to rely on transitive includes, and instead one should explicitly include all direct dependencies. (Note that this does not apply for "master include" headers that are intended to give transitive includes).


This has nothing to do with design patterns. You would include B.h whenever you need to use the class B, and you would include A.h whenever you need to use the class A. If the class B is a design detail of class A, or otherwise closely associated with it, put it in A.h rather than in a separate header file.


I'd like to point out that when you do have header files, you should have a define to make sure it isn't included twice.

For example:

A.h:

#ifndef _A_H_
#define _A_H_

class A 
{
};

#endif

B.h:

#ifndef _B_H_
#define _B_H_

#include "a.h"

class B : public A
{
};

#endif

I think the above makes the most sense because now you can include A and B as many times as you think you'll need, but it won't be compiled multiple times.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号