When writing a program in C ++, you often need to call other functions in a function. In this case, you will consider using a function pointer. A function can call other functions. In a well-designed program, each function has a specific purpose, the use of common function pointers.
First, let's look at the following example:
- # Include<String>
-
- # Include<Vector>
-
- # Include<Iostream>
-
- Using namespace std;
-
-
- Bool IsRed (string color ){
-
- Return (Color= "Red ");
-
- }
-
-
- Bool IsGreen (string color ){
-
- Return (Color= "Green ");
-
- }
-
-
- Bool IsBlue (string color ){
-
- Return (Color= "Blue ");
-
- }
-
-
- Void DoSomethingAboutRed (){
-
- Cout<<"The complementary color of red is cyan! \ N ";
-
- }
-
-
- Void DoSomethingAboutGreen (){
-
- Cout<<"The complementary color of green is magenta! \ N ";
-
- }
-
-
- Void DoSomethingAboutBlue (){
-
- Cout<<"The complementary color of blue is yellow! \ N ";
-
- }
-
-
- Void DoSomethingA (string color ){
-
- For (intI=0; I< 5; ++ I)
-
- {
-
- If (IsRed (color )){
-
- DoSomethingAboutRed ();
-
- }
-
- Else if (IsGreen (color )){
-
- DoSomethingAboutGreen ();
-
- }
-
- Else if (IsBlue (color )){
-
- DoSomethingAboutBlue ();
-
- }
-
- Else return;
-
- }
-
- }
-
-
- Void DoSomethingB (string color ){
-
- If (IsRed (color )){
-
- For (intI=0; I< 5; ++ I ){
-
- DoSomethingAboutRed ();
-
- }
-
- }
-
- Else if (IsGreen (color )){
-
- For (intI=0; I< 5; ++ I ){
-
- DoSomethingAboutGreen ();
-
- }
-
- }
-
- Else if (IsBlue (color )){
-
- For (intI=0; I< 5; ++ I ){
-
- DoSomethingAboutBlue ();
-
- }
-
- }
-
- Else return;
-
- }
-
-
- // Use the function pointer as a parameter. The default parameter is & IsBlue
-
- Void DoSomethingC (void (* DoSomethingAboutColor) () = & DoSomethingAboutBlue ){
-
- For (intI=0; I< 5; ++ I)
-
- {
-
- DoSomethingAboutColor ();
-
- }
-
- }
We can see that in the DoSomethingA function, the color value needs to be determined once for each loop. These are repeated judgments. In C ++ programming, the for loop is repeatedly written three times, the code is not refined. If we use the function pointer here, we can judge the color value only once and write the for loop only once. DoSomethingC provides the code that uses the function pointer as the function parameter, doSomethingD provides the code that uses string as the function parameter.