1> 〉
Class {
Public:
Virtual void F () {cout <"A: F" <Endl ;};
};
Class B: Public {
Public:
Virtual void F () {cout <"B: F" <Endl ;};
};
Class C: Public {
Public:
Virtual void F () {cout <"C: F" <Endl ;};
};
Void test (A * ){
A-> F ();
};
Int main (INT argc, char * argv [])
{
B * B = new B;
C * c = new C;
Char choice;
Do {
Cout <"type B for Class B, C for Class C:" <Endl;
Cin> choice;
If (choice = 'B '')
Test (B );
Else if (choice = 'C '')
Test (C );
} While (1 );
Cout <Endl;
Return 0;
}
Output result:
B: F
C: F
Conclusion: Test (A * A) actually has an implicit conversion process from an inherited class pointer to a base class pointer. We can see that using the virtual function, we can call the inheritance class function in the base class. If it is not a virtual function, the inherited class pointer can only call the base class function after being converted to the base class pointer. Conversely, if the base class pointer is converted to the inherited class pointer, it can only display the conversion. After the conversion, the inherited class pointer can call the base class and the inherited class pointer.