Sams Teach Yourself C++ in 21 Days

(singke) #1
Special Classes and Functions 525

73: void GetVals (int & rValOne, int & rValTwo)^15
74: {
75: cout << “New value for ValOne: “;
76: cin >> rValOne;
77: cout << “New value for ValTwo: “;
78: cin >> rValTwo;
79: }

(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1
x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3
x: 2 y: 3
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 y: 3
x: 8 y: 27
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 y: 729
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 y: 729
x: 729 y:64
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0
On line 17,pFuncis declared to be a pointer to a function returning voidand
taking two parameters, both integer references. On line 9,PrintValsis declared
to be a function taking three parameters. The first is a pointer to a function that returns
voidbut takes two integer reference parameters, and the second and third arguments to
PrintValsare integer references. The user is again prompted on lines 19 and 20 for
which functions to call, and then on line 33 PrintValsis called using the function
pointer,pFunc, as the first parameter.
Go find a C++ programmer and ask him what this declaration means:
void PrintVals(void (*)(int&, int&),int&, int&);
This is the kind of declaration that you use infrequently and probably look up in the
book each time you need it, but it will save your program on those rare occasions when it
is exactly the required construct.

Using typedefwith Pointers to Functions ....................................................


The construct void (*)(int&, int&)is cumbersome, at best. You can use typedefto
simplify this, by declaring a type (in Listing 15.9, it is called VPF) as a pointer to a func-
tion returning voidand taking two integer references. Listing 15.9 rewrites Listing 15.8
using this typedefstatement.

OUTPUT


LISTING15.8 continued


ANALYSIS
Free download pdf