Use function pointers as a function parameter : function pointers « Function « C++ Tutorial

Home
C++ Tutorial
1.Language Basics
2.Data Types
3.Operators statements
4.Array
5.Development
6.Exceptions
7.Function
8.Structure
9.Class
10.Operator Overloading
11.Pointer
12.File Stream
13.template
14.STL Introduction
15.string
16.vector
17.list
18.bitset
19.set multiset
20.valarray
21.queue stack
22.deque
23.map multimap
24.STL Algorithms Modifying sequence operations
25.STL Algorithms Non modifying sequence operations
26.STL Algorithms Binary search
27.STL Algorithms Sorting
28.STL Algorithms Merge
29.STL Algorithms Min Max
30.STL Algorithms Iterator
31.STL Algorithms Heap
32.STL Algorithms Helper
C / ANSI-C
C Tutorial
C++
Visual C++ .NET
C++ Tutorial » Function » function pointers 
7.10.3.Use function pointers as a function parameter
#include <iostream>
 using namespace std; 
 
 void Square (int&,int&);
 void Cube (int&, int&);
 void Swap (int&, int &);
 void GetVals(int&, int&);
 void PrintVals(void (*)(int&, int&),int&, int&);
 
 int main()
 {
     int valOne=1, valTwo=2;
     void (*pFunc)(int&, int&);
 
     pFunc = GetVals; 
     PrintVals pFunc, valOne, valTwo);

     pFunc = Square; 
     PrintVals pFunc, valOne, valTwo);

     pFunc = Cube; 
     PrintVals pFunc, valOne, valTwo);

     pFunc = Swap; 
     PrintVals pFunc, valOne, valTwo);
 
     return 0;
 }
 
 void PrintValsvoid (*pFunc)(int&, int&),int& x, int& y)
 {
     cout << "x: " << x << " y: " << y << endl;
     pFunc(x,y);
     cout << "x: " << x << " y: " << y << endl;
 }
 
 void Square (int & rX, int & rY)
 {
     rX *= rX;
     rY *= rY;
 }
 
 void Cube (int & rX, int & rY)
 {
     int tmp;
 
     tmp = rX;
     rX *= rX;
     rX = rX * tmp;
 
     tmp = rY;
     rY *= rY;
     rY = rY * tmp;
 }
 
 void Swap(int & rX, int & rY)
 {
     int temp;
     temp = rX;
     rX = rY;
     rY = temp;
 }
 
 void GetVals (int & rValOne, int & rValTwo)
 {
     cout << "New value for ValOne: ";
     cin >> rValOne;
     cout << "New value for ValTwo: ";
     cin >> rValTwo;
 }
x: 1 y: 2
New value for ValOne: 1
New value for ValTwo: 2
x: 1 y: 2
x: 1 y: 2
x: 1 y: 4
x: 1 y: 4
x: 1 y: 64
x: 1 y: 64
x: 64 y: 1
7.10.function pointers
7.10.1.Using function pointers
7.10.2.Arrays of pointers to functions
7.10.3.Use function pointers as a function parameter
7.10.4.Use typedef to define a function type for function pointer
7.10.5.arguments passed by reference
7.10.6.arguments passed by pointer
7.10.7.array passed by pointer
7.10.8.orders two arguments using pointers
7.10.9.sorts an array using pointers
7.10.10.Function pointer for overloaded function
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.