Read: 30 comments: 0 Author: Mini database published on original article link
From Baidu encyclopedia
I,What is a virtual function (if you don't know what the virtual function is, but want to know it urgently, you should start from here)
Simply put, member functions modified by virtual keywords are virtual functions. The role of virtual functions is explained in professional terms by implementing polymorphism. polymorphism separates interfaces from implementations. interpreting with image languages means implementing a common approach, however, different strategies are adopted due to individual differences. Let's take a look at a simpleCode
Class {
Public:
Void print () {cout <"This is a" <Endl ;}
};
Class B: Public {
Public:
Void print () {cout <"This is B" <Endl ;}
};
Int main () {// for future convenience, the main () code is called main1
A;
B;
A. Print ();
B. Print ();
}
Through the print () interface of Class A and Class B, we can see that these two classes adopt different policies due to individual differences, and the output results are also expected, this is a and this is B, respectively. But does this actually enable polymorphism? No,Another key to polymorphism is that all objects are operated by pointers or references to the base class.. Now let's change the code in main.
Int main () {// main2
A;
B;
A * P1 = &;
A * P2 = & B;
P1-> Print ();
P2-> Print ();
}
Run the command to check the result. The problem is that P2 points to the Class B object but calls the print () function of Class A, which is not the expected result, to solve this problem, you need to use virtual functions.
Class {
Public:
Virtual void print () {cout <"This is a" <Endl ;}// it is now a virtual function.
};
Class B: Public {
Public:
Void print () {cout <"This is B" <Endl;} // do I need to add the keyword virtual in front of it?
};
Without a doubt, the print () member function of Class A has become a virtual function, so does the print () of Class B become a virtual function? The answer is yes. We only need to set the member functions of the base class to virtual, and the corresponding functions of the derived class will automatically become virtual functions. Therefore, print () of Class B is also a virtual function. If you need to use the virtual keyword to modify the corresponding function of the derived class, it is your own problem.
Run the main2 code again. The output result is this is a and this is B.
Post comments
News Channel: The 30 most failed technology products in the past 10 years
Recommended link: Windows 7 topic release
website navigation: blog home page personal homepage news community blog flash memory Knowledge Base