Static type and dynamic type
concept
The so-called static type refers to the type of variable declaration; and the dynamic type is the type of variable actually pointing.
characteristic
The static type is quiet, and once it is determined to change without changes; the dynamic type can be changed according to the actual pointing. Static type control static binding, dynamic type control dynamic binding.
E.g:
Class B;
Class D: public B;
B * Pb; // Static type is not B, dynamic type is not unknown
B b; // Static type is B, dynamic type is B
D * pd; // static type is D, dynamic type is not known
D D; // Static type D, dynamic type is D
/ * At this point, the static type of each variable has been fixed, and the dynamic type of B and D is also fixed; and the dynamic type of the pointer variable may vary. * /
PB = & b; // PB dynamic type B
PB = & D; // PB dynamic type Du D
PD = (d *) & b; // PD dynamic type B
PD = & D; // PD dynamic type Di D
B = D; // B static type is B, dynamic type is B
In addition to virtual functions are dynamic bindings, the rest are static bindings (such as default parameters
Test case
#include
Class B
{
PUBLIC:
Void f ()
{
COUT << "bf" << endl;
}
Virtual Void V (Char C = 'B')
{
COUT << "BV -" << c << endl;
}
}
Class D: Public B
{
PUBLIC:
Void f () // error! This kind of practice is hidden, do not advocate!
{
COUT << "DF" << ENDL;
}
Virtual Void V (Char C = 'D') // Error! Does not allow the default value, otherwise the program is unexpected, see the output result
{
COUT << "DV -" << c << endl;
}
}
void main ()
{
B B, * PB;
D D, * Pd;
PB = & D;
Pb-> f ();
PB-> V ();
PD = (d *) & b;
PD-> f ();
PD-> V ();
}
The output is as follows:
BFDV-BDFBV-D