We know that when the header file on which a source file is dependent is modified, the source file needs to be re-compiled (the fragile base class problem). In order to introduce the method I will describe, let's take a look at a simple example. The Code is as follows:
View plain
// Head. h
Struct
{Int I ;};
Class B
{
A *;
Public:
B (int n = 0 );
Void show ();
~ B ();
};
// Head. cpp
# Include "head. h"
# Include <iostream. h>
B: B (int n)
{
A = new;
A-> I = n;
}
Void B: show ()
{
Cout <a-> I;
}
B ::~ B ()
{
Delete;
}
// Main. cpp
# Include <iostream>
# Include "head. h"
Using namespace std;
Int main ()
{
B B (1 );
B. show ();
Return 1;
}
If we want to modify the struct A, for example, we need to add A member variable to A, then head. h is changed to include its head. cpp and main. cpp both need to be re-compiled.
We know that Class B is A handle class that encapsulates Class A. In this form, how can we modify the code so that the definition of Class A can be reduced and re-compiled?
After observing head. h, we found that Class A does not need to be fully defined in the Declaration process of Class B. We Can slightly modify the code using this point. The modified code is as follows:
// Head. h
Class B
{
Struct A; // incomplete class type description
A *;
Public:
B (int n = 0 );
Void show ();
~ B ();
};
// Head. cpp
# Include "head. h"
# Include <iostream. h>
Struct B: full definition of A //
{
Int I;
};
B: B (int n)
{
A = new;
A-> I = n;
}
Void B: show ()
{
Cout <a-> I;
}
B ::~ B ()
{
Delete;
}
// Main. cpp
# Include <iostream>
# Include "head. h"
Using namespace std;
Int main ()
{
B B (1 );
B. show ();
Return 1;
}
After this modification, if we need to modify the definition of A, we only need to modify head. cpp to avoid the need to redefine main. cpp.
Conclusion: if there is a handle class in our system and the system is very large, we may need this so-called trick to avoid excessive Compilation Time.
Author: yucan1001