First look at the code below, create a parent class, then subclass inherits the parent class in to one, two class has its own play () method, in the first 35-37 lines of code to create a parent pointer then subclass address assignment by reference to the parent class, then call the pointer P play () method will print out what yet. I thought it would be a subclass of calling play () method, because to quote the line 36, but the print result is:
This play is a parent class
. 1 #include <the iostream> 2 . 3 class Father . 4 { . 5 public : . 6 void play () . 7 { . 8 STD :: COUT << " This is the play of a parent class " << STD :: endl; . 9 } 10 }; . 11 12 is class Son: public Father 13 is { 14 public : 15 void Play () 16 { . 17 STD :: COUT << " this is subclasses Play" << std::endl; 18 } 19 }; 20 21 22 void party(Father** men, int num) 23 { 24 for (int i = 0; i < num; i++) 25 { 26 men[i]->play(); 27 } 28 } 29 30 int main() 31 { 32 Father father; 33 Son son; 34 35 Father* p; //A pointer P is defined parent class 36 P = & Son; // pointer references subclass address 37 [ p-> play (); // play accessing pointers () method, the access will be play subclass () it? 38 is 39 }
Access method in the subclass of parent class through a pointer, this situation often encountered in the project. If you want to access a subclass method pointer by a parent class in how to do it? Just add a keyword before the relevant parent class method: virtual
The following code:
. 1 #include <the iostream> 2 . 3 class Father . 4 { . 5 public : . 6 virtual void play () // in the parent class play () method of increasing virtual keyword before . 7 { . 8 STD :: COUT << " This is a parent class Play " << STD :: endl; . 9 } 10 }; . 11 12 is class Son: public Father 13 is { 14 public : 15 void Play () 16 { 17 std::cout << "这是个子类的Play" << std::endl; 18 } 19 }; 20 21 22 void party(Father** men, int num) 23 { 24 for (int i = 0; i < num; i++) 25 { 26 men[i]->play(); 27 } 28 } 29 30 int main() 31 { 32 Father father; 33 is Son Son; 34 is 35 Father * P; // pointer to a parent class definition P 36 P = & Son; // pointer references subclass address 37 [ p-> Play (); // Play accessing pointers () method, the visit will be the play subclass () Why? 38 is 39 }
Operating results as follows:
This is a sub-class of Play
==========================================================================================================================