[C ++ Basics] 035_pointer function and function pointer

Source: Internet
Author: User

1. Preface

With regard to pointer functions and function pointers, especially function pointers, I believe many C/C ++ ers have the same reverence for them as I used to, and think they are very advanced. In fact, they are not. It won't take much effort to understand it. Maybe I can tell the difference in one sentence, but it just forms a concept in my mind. In the college age, when I was a student, I could finish reading Mao summary in one day and get an exam of 80 or 90 points; however, I spent a week reading tan haoqiang's c ++ teaching materials (although many people despise this teaching material), but I still have no way to start on the computer. I can talk about it and get familiar with all concepts, however, the program cannot be compiled. This is the world of programmers. Only by doing everything can we understand the true meaning. However, this should also prove a famous qiangu sentence, which is also my favorite poem "the end of the paper is very simple, and I am absolutely sure that this matter will be done ".

All code compilation and Running Environments in this article: Windows 7 javassionnal, visual studio2010 professional.

2. Overview

According to the General-minute-general structure of the article, here we will give a general introduction to the concepts of pointer functions and function pointers, and then introduce them in detail using programs. The following describes the concepts of pointer functions and function pointers.

[Pointer function]: returns the pointer function. The point is that it is a function, but the return value is changed from a common value or object to a pointer. That is to say, this function returns a memory address.

[Function pointer]: pointer to a function. The point is that it is a pointer, but the content it points to is changed from a common variable or object to a function, that is, it can point to the function entry address.

3. pointer Functions

Before introducing pointer functions, let's look at a common function.

 1 #include <iostream> 2 using namespace std; 3  4 class MyType{ 5 public: 6     MyType(int value):m_value(value){ 7         cout<<"Construct."<<endl; 8     } 9     ~MyType(){10         cout<<"Desconstruct."<<endl;11     }12 public:13     int m_value;14 };15 16 MyType getInstanceOfMyType(){17     MyType mt(10);18     cout<<&mt<<endl;19     return mt;20 }21 22 int main(){23 24     MyType mt = getInstanceOfMyType();25     cout<<&mt<<endl;26     cout<<mt.m_value<<endl;27 28     system("pause");29     return 0;30 }

The coloring part is what we need to pay attention to. The function "getinstanceofmytype ()" internally creates a mytype object, outputs the address of the object, and finally returns the object. In the main function, the return value of the function is obtained by calling the function, the address of the returned object is printed, and the value of the m_value attribute of the object is obtained. The output result is as follows:

Construct.0045f688desconstruct. 0045f78810 press any key to continue...

As you can see, in the "getinstanceofmytype ()" function, the object is destroyed after being created. The output shows that the returned object address is different from the object address created in the function, but the value of m_value is the same, this indicates that the normal function obtains a copy of the object created inside the function, which is the processing of the normal function when returning the object.

After seeing the processing of common functions, let's take a look at the processing of a pointer function. Below is a piece of code for the pointer function. Note that this code is very similar to the previous one and should be distinguished.

 1 #include <iostream> 2 using namespace std; 3  4 class MyType{ 5 public: 6     MyType(int value):m_value(value){ 7         cout<<"Construct."<<endl; 8     } 9     ~MyType(){10         cout<<"Desconstruct."<<endl;11     }12 public:13     int m_value;14 };15 16 MyType *getInstanceOfMyType(){17     MyType *mt = new MyType(10);18     cout<<mt<<endl;19     return mt;20 }21 22 int main(){23 24     MyType *mt = getInstanceOfMyType();25     cout<<mt<<endl;26     cout<<mt->m_value<<endl;27 28     system("pause");29     return 0;30 }

Note the part of the Code coloring above, especially the function "getinstanceofmytype ()", which is already a pointer function. So what is the output of this program? As follows:

Construct.00754aa800754aa810 press any key to continue...

It can be seen that the object in the function "getinstanceofmytype ()" has not been called the destructor, and the address of the object inside and outside the function is exactly the same, of course, the value of m_value stored in the object is the same. You may ask, isn't it that the local variable is destroyed after the function is called? Yes, it is destroyed, but it only destroys the "mytype * MT" pointer, but the memory it points to will not be destroyed. Therefore, we can continue to access this object. In this case, we generally need to add our own delete operations outside the function call. The above program does not add such operations, which is strictly a wrong program.

When using a pointer function, directly return the address of the internal object of the function, so that you do not need to re-create a copy of the object, which is helpful for efficiency improvement. However, you must remember to release the memory applied inside the function outside the function, otherwise there is a risk of memory overflow.

4. function pointer

Next we will talk about our main topic today-function pointers. Function pointers are a very useful technique that allows us to execute a function code through pointers. For highly skilled people, it is a perfect sword and can solve many problems. Next, let's look at the function pointer.

First, let's look at the code of the simplest function pointer. Pay attention to the Declaration and call methods.

1 # include <iostream> 2 using namespace STD; 3 4 int printfunc (INT value) {5 cout <"this is a print function. the value is: "<value <Endl; 6 RETURN 0; 7} 8 9 int main () {10 11 int (* pfunction) (int x ); // This is a function pointer variable 12 pfunction = printfunc; // The function entry address is given to function pointer 13 (* pfunction) (7); // The function is obtained through the * operator, then input parameter 7 and execute function 14 15 system ("pause"); 16 return 0; 17}

The coloring part of the code above is the declaration-definition-execution process of the function pointer. As you can see, I only need to give the function entry address to the function pointer to execute the function. Here is a knowledge point about the Function calling method. Generally, the function calling method is as follows: function name (parameter list ), but in fact, the function call method can also be written as follows: (* function name) (parameter list ). You can call a function as follows, but it is rarely used as follows:

1 (*printFunc)(8);

In addition, we can also write (& function name) (parameter list) as follows ). That is, the following function is called, which is rarely used as follows:

1 (&printFunc)(8);

For a function pointer, there are two prerequisites: ①. That is, the returned value of the function pointing to must be consistent with the declared function pointer. ②. The parameter type and number of the function to be pointed to must be consistent with the declared function pointer. Otherwise, compilation fails.

5. function pointer type

The above section directly declares a function pointer when using the function pointer. In fact, function pointers can also be declared as a type by using typedef, so that we can define a function pointer just like defining int variables. The code for defining the function pointer type is as follows:

1 # include <iostream> 2 using namespace STD; 3 4 int printfunc (INT value) {5 cout <"this is a print function. the value is: "<value <Endl; 6 RETURN 0; 7} 8 typedef int (* pfunction) (int x); // function pointer type, note the return value and Parameter List 9 10 int main () {11 12 pfunction ptrfunc; // define the function pointer variable 13 ptrfunc = printfunc; 14 (* ptrfunc) (1 ); // Method 15 ptrfunc (2); // Method 16 17 system ("pause"); 18 return 0; 19}

6. Example of a function pointer

1 # include <iostream> 2 using namespace STD; 3 4 typedef void (* pfunction) (int x); // function pointer type, note the return value and Parameter List 5 6 void printa (INT value) {7 cout <"A-" <value <Endl; 8} 9 10 void printb (INT value) {11 cout <"B-" <value <Endl; 12} 13 14 void printc (INT value) {15 cout <"C-" <value <Endl; 16} 17 18 int main () {19 int choice; 20 pfunction ptrfunc [3] = {printa, printb, printc}; 21 CIN> choice; 22 ptrfunc [choice] (choice); 23 24 system ("pause"); 25 return 0; 26}

I will not explain it here. The code is very short and easy to understand.

7. Conclusion

This article provides a simple introduction to pointer functions and function pointers. I hope that you will have a deep understanding of pointer functions and function pointers after reading this article. Of course, the purpose of writing this article is to strengthen the author's c ++ basics.

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.