Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
A Complete Guide to Programming in C++ part 72. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | POINTERS TO FUNCTIONS 689 Using Pointers to Functions In C the name of a function is a constant pointer to that function. It addresses the machine code for the function. This is a situation that we have already seen for arrays the array name is also a constant pointer to the first array element. There are many uses for pointers to functions. You can save them in an array to form a jump table. Individual functions are then accessible via an index. A pointer to a function can also be passed as an argument to another function. This makes sense if the function you are calling needs to work with different functions depending on the current situation. The standard function qsort is an example of this. qsort uses the quick sort algorithm to sort an array. Depending on the type of the array elements and the sort criteria the qsort function will expect as argument another comparison function. Declaring Pointers to Functions A pointer to a function is declared as follows Syntax type funcptr parameter_list This defines the variable funcptr which can store the address of a function. The function has the type type and the parameter list stated. The first pair of parentheses is also important for the declaration. The statement type funcptr parameter_list would declare a function funcptr that returned a pointer. Now let s point funcptr to the function compare and call compare via the pointer. Example bool compare double double Prototype bool funcptr double double funcptr compare funcptr 9.1 7.2 Calling funcptr is now equivalent to calling compare . The declaration of compare is necessary to let the compiler know that compare is the name of a function. In the program shown opposite functab is an array with four pointers to functions of the void type each of which expects a C string as an argument. functab is initialized by the functions stated in its definition and thus functab 0 points to error_message functab 1 to message etc. When the program is executed the function with the .