A special function in C ++ programming language is called a virtual function. How should we correctly understand C ++ virtual functions? Here we will give a detailed introduction to the basic concepts in this aspect, hoping to help you and increase your awareness of the C ++ language.
I think I have mastered the role of virtual functions. Wow, I didn't say I was an old bird, or I understand it, but it cannot be used in practice. Don't worry. Let me talk about it for the last time.
What is a virtual function? The C ++ virtual function is a function described by the keyword "Explain aul.
For example:
In this example, WindowB and WindowC do not exist at the same time, which is often used in practical applications to save memory.
- Class sort wa
- {
- Public:
- Virtual void Draw (){};
- };
- Class Using WB: public using wa
- {
- Public:
- Using WB (){};
- Void Draw ();
- };
- Class sort WC: public sort wa
- {
- Public:
- WindowC (){};
- Void Draw ();
- };
- Void required WB: Draw ()
- {
- Draw a circle;
- }
- Void merge WC: Draw ()
- {
- Draw a square;
- }
When WindowA is defined, you are not sure what the derived classes of WindowB and WindowC will Draw in the Draw function. In this case, the Draw is defined as a C ++ virtual function, which is implemented in the derived class.
Speaking of this, the reader will ask: I will write Draw in WindowB and WindowC, and I will write less of a kind of mongowa.
Yes, it's just a matter of writing. As you said, you will use it like this:
- Required WB * B = new required WB;
- B-> Draw (); // Draw a circle
- Delete B;
- WindowC * c = new WindowC;
- C-> Draw (); // Draw a square
- Delete c;
I use pointers here. In the code above, B and c are two independent object pointers. But what should you do if there are dozens or hundreds of derived classes instead of one or two? How many hundred variables are defined in the header file?
No, it's time to use the C ++ virtual function:
- WindowA * a = new WindowsB;
- A-> Draw (); // Draw a circle. The implementation of the Draw function in WindowB is called here.
- Ifa)
- Delete a; // The new value must be deleted.
- WindowA * a = new WindowC;
- A-> Draw (); // Draw a square. The implementation of the Draw function in WindowC is called here.
- Ifa)
- Delete;
In the above Code, a implements a transit variable. As long as it is derived from megawa, I can assign a value to a, and B and c are both temporary variables. The number of derived classes of megawa is okay. I just need to define a pointer variable of megawa in the header file.