|
|
|
|
|
|
|
At times, you will want to grant the friend level of access, not to an entire class, but to only one or two functions of that class. You can do this by declaring the member functions of the other class to be friends, rather than declaring the entire class to be a friend. In fact, you can declare any function, whether or not it is a member function of another class, to be a friend function. |
|
|
|
|
|
|
|
|
Just as an array name is a constant pointer to the first element of the array, a function name is a constant pointer to the function. It is possible to declare a pointer variable that points to a function, and to invoke the function by using that pointer. This can be very useful; it allows you to create programs that decide which functions to invoke based on user input. |
|
|
|
|
|
|
|
|
The only tricky part about function pointers is understanding the type of the object being pointed to. A pointer to int points to an integer variable, and a pointer to a function must point to a function of the appropriate return type and signature. |
|
|
|
|
|
|
|
|
funcPtr is declared to be a pointer (note the * in front of the name) that points to a function that takes an integer parameter and returns a long. The parentheses around * funcPtr are necessary because the parentheses around int bind more tightlythat is, they have higher precedence than the indirection operator (*). Without the first parenthesis, this would declare a function that takes an integer and returns a pointer to a long. (Remember that spaces are meaningless here.) |
|
|
|
|
|
|
|
|
Examine these two declarations: |
|
|
|
|
|
|
|
|
long * Function (int);
long (* funcPtr) (int); |
|
|
|
|
|
|
|
|
The first, Function (), is a function taking an integer and returning a pointer to a variable of type long. The second, funcPtr, is a pointer to a function taking an integer and returning a variable of type long. |
|
|
|
|
|
|
|
|
The declaration of a function pointer will always include the return type and the parentheses indicating the type of the parameters, if any. Listing 20.5 illustrates the declaration and use of function pointers. |
|
|
|
|
|