So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Put only member function declarations in header (.h) files, and put member function definitions in implementation (.cpp) files. Then your header files do not need to include each other, and you can include both headers in either implementation file.
For cases when you need to reference the other class in member signatures as well, you can use a forward declaration:
This lets you use pointer and reference types (
A*
andA&
), though notA
itself. It also doesn't let you call members.Example:
You can also use forward declarations to get around the issue.
Try putting
#ifndef
,#define
and#endif
around your .h files.Each class (A and B) should have a header file and an implementation file.
Each header file (e.g.
A.h
) should not include the other header file (e.g.B.h
) but may include a forward reference to the other class (e.g. a statement likeclass B;
), and may then use pointers and/or references to the other class in its declaration (e.g.class A
may contain aB*
as a data member and/or as a method parameter).Each CPP file (e.g.
A.cpp
) may include more than one header file (e.g.A.h
andB.h
). It's recommended that each CPP file should include its own header file first (e.g.A.cpp
should includeA.h
and thenB.h
, whereasB.cpp
should includeB.h
and thenA.h
).Each header file should contain only the declaration, and not the definition of the class: for example it will list the signatures of the class' methods, but not the method bodies/implementations (the method bodies/implementations will be in the
.cpp
file, not in the header file). Because the header files don't contain implemention details, they therefore don't depend on (don't need to see) details of other classes; at most they need to know that, for example,B
is the name of a class: which it can get from a forward declaratin, instead of by including a header file in another header file.