若设计一个结构体三个类,和一堆宏定义以及一堆常量以及一堆全局函数:
#define ABC 1
#define DEF 2
int const MIN;
int funa(...);
int funb(...);
struct a;
class x;
class y;
class z;
其中,宏定义、常量、常量函数放在common.h
中;class x
拥有一个成员变量是class y
的实例;class y
拥有一个成员变量是class x
的实例;class z
的大部分成员方法都会用到class x
和class y
;
请问,如果要分成若干个.h
文件和若干个.cpp
文件,该如何写?
This. . Unless you use pointers, it’s impossible
The pointer is as follows:
common.h
common.cpp
classx.h
classx.cpp
classy.h
classy.cpp
classz.h
classz.cpp
main.cpp
common.h
classx.h
classy.h
classz.h
Owner, are you afraid of circular references and causing errors? If this is the case, it is recommended that you take a look at C++ class forward declaration, which is enough to solve your problem.
It’s C++ anyway, so all constants should be able to be turned into constexpr.
This cannot be solved by forward declaration. The compiler needs to know the complete definition of class y when compiling class x. To know the complete definition of class y, it must first know the definition of class x. The compiler will tell you "I can't figure it out". If you have to do this, you can use a pointer: class x has a pointer to an instance of class y. The compiler knows what the pointer is, and the same applies to class y.
This is to use forward declaration, but only pointers or references can be used, because the compiler must clarify the size of the members when compiling, and the sizes of pointers and references are determined.
It’s like designing a house and a bed. Where can I buy a bed before the house is designed? The size is unknown, but pointers can be used.