Suppose there is a date class
Date.h
- Class Date {
- Private
- int year, month, day;
- };
If the definition of a task class is to be used with the date class, there are two ways to
One
Task1.h
- Class Date;
- Class Task1 {
- Public
- Date GetData ();
- };
Second
Task2.h
- #include "Date.h"
- Class Task2 {
- Public
- Date GetData ();
- };
One uses the predecessor declaration, and one uses #include<date.h> to add the definition of Date. Both of these methods can be compiled. But Task1.h this is better. If the private member variable of the Date.h changes, such as a double year, month, day; , Task1.h does not need to be recompiled, and Task2.h is recompiled, and, worse, if Task2.h has dependencies on many other header files, it can lead to a cascade of recompilation, which takes a lot of time. But in fact, changing the way you can save a lot of effort.
So When you can use a predecessor declaration instead of # include, try to use the forward declaration
There are cases where a predecessor declaration cannot be used in place of # include
For example, Task1.h changed into
- Class Date;
- Class Task1 {
- Public
- Date D;
- };
Compiles an error because date D defines a date type variable, and the compiler must know the size of D when allocating memory space for D, and must include the Date.h file that defines the date class.
It is possible to use pointers instead
- Class Date;
- Class Task1 {
- Public
- Date *d;
- };
The size of the pointer is fixed. On a 32-bit machine is 4 bytes, and 64-bit machines are 8 bytes. The size of date is not required when compiling Task1, so it has nothing to do with the definition of date.
When can I replace # include with a predecessor declaration
(http://blog.csdn.NET/rogeryi/archive/2006/12/12/1439597.aspx)
The above example can illustrate
If you can accomplish a task using object reference or object point, do not use object
This can be done to the maximum extent possible to avoid # include
Provides different header files for declarative and defined
During the design of the library, the design of the interface should follow the above criteria.
The header file for an interface is like this
Interface.h
- Class Date;
- Class Address;
- Class Email;
- Date getDate ();
If the customer only uses the date class, the compiler will only compile Date.h, not compile address.h,email.h and so on.
Predecessor declarations and header files