C ++ those details-function pointer

Source: Internet
Author: User
Tags define function

C ++ those details-function pointer
I. Introduction The most flexible stuff in C or C ++ is Pointer. When operating an object, or an array, we often use pointers, which can bring a lot of flexibility to programming. However, pointers can not only point to fixed data types or objects, but also to functions. This is called function pointers. With the function pointer, we can call a function through the pointer. More importantly, we can pass the function pointer as a parameter to the function to complete registration, callback, and other functions, with function pointers, our program can be designed more flexibly. Ii. Common function pointers 1. The simplest example of defining a function pointer is as follows:

// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
 
  
# Include
  
   
# Include
   
    
Using namespace std; // define a function pointer void (* pFunc) (int); // declare and define a function void PrintInt (int I) {cout <
    
     
Result: 1. Press any key to continue... when declaring a function pointer, the general format is the return value (* function pointer name) (parameter 1, parameter 2 ...) but this declaration has a drawback, that is, the trouble. Every time you need a function pointer, you need to write such a large string, which is very troublesome. So we thought of using the typedef keyword, define a function pointer of a type and give it an alias so that every time you use this function pointer, it can be as simple as defining an int variable. For example, the above function pointer can be written as follows:
     
// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
      
       
# Include
       
        
# Include
        
         
Using namespace std; // use typedef to define the function pointer. In this case, pFunc is no longer the name of the function pointer, but an alias of this type of function pointer, typedef void (* pFunc) (int); // declare and define a function void PrintInt (int I) {cout <
         
          
Result: 1. Press any key to continue... after this writing, we define a function pointer type. The return value is void, and the parameter is an int function pointer, then, you can use pFunc to easily define function pointers of this type! Iii. member function pointer
          

The member function pointer is one of the most troublesome tasks in C ++. It is a non-static member function pointer.

1. static member function pointer

The static member function pointer is the same as the normal function pointer. Let's look at an example:

 

// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
           
            
# Include
            
             
# Include
             
              
Using namespace std; // Base class Base {public: static void Print (int num) {cout <
              
               

 

Result:

1. Press any key to continue...

Static member functions are no different from common functions. Although they are defined in classes, they do not process different member functions because they do not have the this pointer, so we can regard it as a common function.

 

2. Non-static member functions

 

But non-static member function pointers are much more troublesome, because non-static member functions have a hidden parameter -- this pointer, which is different among different objects, so it is very troublesome. When defining non-static member function pointers, We need to write the object type. This function must also be called based on the corresponding object. Let's look at an example:

 

// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
                
                 
# Include
                 
                  
# Include
                  
                   
Using namespace std; // Base class Base {public: void Print (int num) {cout <
                   
                    
Result:
                    

 

1. Press any key to continue...

 

Analyze the definition and usage of the member function pointer. In this way, we define the function pointer (Base: * pFunc) (int), which is actually equivalent to (* pFunc) (Base *, int), which is equivalent to a common function pointer. One more this pointer is required as a parameter, and this pointer must be different among different objects. Therefore, member function pointers cannot be converted to each other, only functions of the same type of objects can be assigned to function pointers of such objects.

When assigning values to pointers, pay attention to the writing method. When assigning values to common function pointers, you can leave no & symbol, but the assignment of member function pointers is strict, if this parameter is not specified, the following error will be reported:

Error C3867: "Base: Print": the function call lacks a parameter list. Use "& Base: Print" to create a pointer to a Member.

In addition, do not assign values to objects when assigning values. Use Class Name: function name to assign values. When using object name. function name, the following error is reported:

Error C2276: "&": Illegal operation on the function expression bound to the member

It can be seen that the writing of member function pointers is still quite rigorous.

Finally, let's analyze the usage. Because the member function pointer requires a this pointer as a parameter, this parameter cannot be provided directly, so we can only call the function through the object. When using the function, because the function is a whole, you need to use (). Inside the brackets, we get the function through * func, and then use base. the base is passed to the function as the this pointer.

 

So, since this function is a non-static member function, does this function support dynamic binding? In other words, the declared function pointer is the function pointer of the base class. When the subclass overwrites this function, when the subclass object is called, does it call a base class function or a subclass function? Let's look at an example:

 

// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
                     
                      
# Include
                      
                       
# Include
                       
                        
Using namespace std; // Base class Base {public: // virtual void Print (int num) {cout <
                        
                         
Result:
                         

 

Base: 1 child: 1 sizeof Member Function: 4 press any key to continue...

 

From the above results, we can see that when using the function pointer at last, the object of this pointer can be a subclass of the object when we declare the function pointer, in addition, if we overwrite the base class functions, we can call the sub-class functions (note that the virtual functions of the base class are overwritten, if only the coverage is simple, there is no polymorphism effect ).

Let's analyze the cause. Let's look at this function pointer as a normal function pointer and add a Class Object's this pointer as a parameter. We can declare this parameter as a base class pointer, when we give a real parameter, we can give the base class object, of course, to the subclass object, which is the same as passing a parameter in our common function, and then passing this parameter in, if there is a virtual function, it can trigger polymorphism. However, when assigning values to function pointers, we can only use base-class functions, because we do not declare sub-class functions.

 

4. function pointer function 1. with function pointers as function parameters, we can pass a function as a parameter to another function just like passing a common pointer, which greatly increases the flexibility of programming. For example, to process a transaction, we can change the handler at will. Of course, through polymorphism, we can also implement corresponding functions using object-oriented thinking. Let's look at an example:
// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
                          
                           
# Include
                           
                            
# Include
                            
                             
Using namespace std; // defines the type of Type typedef int (* pcall) (int, int) of the pcall function pointer; // processing function, take a pcall type function as the void Func (pcall p, int x, int y) {cout <
                             
                              
Result: begin func: result is: 3end funcbegin func: result is: 1end func. Press any key to continue...
                              

 

2. Function callback can pass functions as parameters, which is not our final goal. One of the most useful functions of function pointers is callback. For common function calls and callbacks, we use shopping as a metaphor. Common calls are like buying something directly and buying something at the store; function callback is like booking a cake at a cake shop. Then, the cake shop will definitely leave your contact information. When the cake is ready, the cake shop will call you and ask you to get the cake. From here, we can see that function callback also requires some prerequisite steps. First, we need to register the callback function with the caller. This is like we leave contact information at the cake shop, when a certain condition is met, the callback function is called. In our example, the condition is cake ready. Finally, the cake shop calls you to get the cake. This process is to call the registered function. What are the advantages of callback functions? Let's take the example of buying a cake. If callback function is not required, we don't know when to make the cake after going to the cake shop to buy it, so either we have to stay in the cake shop, or we have to call the cake shop and ask if the cake is ready. Let's look at an example that does not use a callback function:
// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
                               
                                
# Include
                                
                                 
# Include
                                 
                                  
Using namespace std; class Baker {private: int m_iTime; // time for cake preparation static const int m_iMaxTime = 10; // assume that the cake is made in public in 10 minutes, if true is returned, otherwise falsebool MakeCake (); // constructor Baker () ;}; Baker: Baker (): m_iTime (0) {} bool Baker :: makeCake () {// assume that every time this function is called, m_iTime + 1m_iTime + = 1; if (m_iTime = m_iMaxTime) {cout <the cake is ready! <
                                  
                                   
Result: The cake is not prepared. The cake is not prepared! Let me get the cake! Press any key to continue .. here, if we want to know whether the cake is ready or not, we must check whether the cake is ready. In other words, we cannot do anything else, so we must always wait for the cake. In the program, our customers keep querying. If this is a thread, this thread cannot continue to do other things during this time .. If we use the callback function, this process becomes like this:
                                   
// C ++ Test. cpp: defines the entry point of the console application. // # Include stdafx. h # include
                                    
                                     
# Include
                                     
                                      
# Include
                                      
                                       
Using namespace std; // declare a callback function typedef void (* CallBackFunc) (void); class Baker {private: int m_iTime; // The time for cake preparation static const int m_iMaxTime = 10; // assume that CallBackFunc m_pfCallBack is finished in 10 minutes; // The callback function is public: // registration: leave the contact information of the person who buys the cake void Invoke (CallBackFunc); // call the person who buys the cake to Notify void groovy (); // If the cake is ready, directly notify the customer of void MakeCake (); // constructor Baker () ;}; Baker: Baker (): m_iTime (0) {} void Baker: MakeCake () {while (m_iTime <m_iMaxTime) {// assume that this function is called every time _ ITime + 1m_iTime + = 1;} cout <cake ready! <
                                       
                                        
Result: your contact information is displayed! Well, just call me. I'm going to play! Cake ready! Let me get the cake! Please press any key to continue... through the function callback, although the implementation process is troublesome, you must first register and then judge inside the class object. However, this is advantageous because the customer does not need to worry about making the cake after registration. As long as the cake is ready, the cake shop will immediately notify the customer. For example, when we perform asynchronous loading, if we need resources, we can register the main thread to load the thread, and then the main thread continues to do other work. After loading the required things, in turn, the main thread is notified through the callback function, so that the loading and main functions can be performed simultaneously, greatly improving the user experience. In fact, the implementation of function pointer callback in C # Is proxy, and C # Makes callback very simple. Unfortunately, there is no proxy in C ++, so it is quite troublesome to do it, however, callback is often useless. 5. Other problems function pointers and pointer functions are just similar to the name and are easy to mix. There is no link between them and they can coexist. The function pointer is a pointer to a function, which is essentially a pointer. A pointer function refers to the return value of a function as a pointer, which is essentially a function. The two are easy to mix:
                                        
// Define a function pointer typedef int (* pFunc) (void); // define a pointer function int * PointerFunc (void) {int a = 1; return & ;}
The function pointer * is put together with the name, and the pointer function * is put together with the return value.
Of course, we can also define the function pointer of a pointer function:
// Define the function pointer typedef int * (* pFUN) (void) for a pointer function );




 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.