First of all, it should be noted that I am not a theoretical school and seldom try to read out-of-class books. I just need to find them when I use them. Therefore, there are deficiencies in theory, leading to insufficient understanding of the "traps" in this article. Of course, for some friends with strong professional knowledge, this is not a "trap", but for my current knowledge level.
Let's give an example to better illustrate the situation. Assume there are two classes and two virtual functions.
# If! Defined father # define fatherclass cfather {public: cfather (); Virtual ~ Cfather (); Virtual void test (); Virtual void Hello ();}; # endif // # include "stdafx. H "# include" father. H "cfather: cfather () {} cfather ::~ Cfather () {} void cfather: Test () {printf ("I am Lao Tzu \ r \ n"); Hello () ;}void cfather: Hello () {printf ("Lao Tzu in High \ r \ n ");} /// // # If! Defined son # define son # include "father. H" class cson: Public cfather {public: cson (); Virtual ~ Cson (); Virtual void test (); Virtual void Hello ();}; # endif // # include "stdafx. H "# include" son. H "cson: cson () {} cson ::~ Cson () {} void cson: Test () {cfather: Test ();} void cson: Hello () {printf ("Son in High \ r \ n ");} /// // # include "stdafx. H "# include" son. H "int main (INT argc, char * argv []) {cson son; son. test (); Return 0 ;}
What are the output results of son. Test?
The actual result is:
I'm Lao Tzu
Son in Hello
That is to say,
Void cfather: Test ()
{
Printf ("I am Lao Tzu \ r \ n ");
Hello ();
}
The Hello () in is not the hello of cfather, but the hello function of cson.
I have written so much code before, and I have never written to call another virtual function in this class in a virtual function ......, therefore, it remains unclear about this mechanism.
What's even more confusing is that in the debug status, you can set a breakpoint on the hello () line of the cfather: test function and view it using the debugger. The function called is a function of the cfather class, instead of cson functions.
After this event, we can find that virtual functions are not defined in disorder. Some friends may like to define a function as a virtual function without considering whether it meets the functional requirements of the virtual function. Therefore, it is easy to produce some incomprehensible phenomena and cause a lot of confusion.
Please correct me if you have any different opinions on such issues.