1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
#include <iostream>
#include <string>
#include<cstdlib>
using namespace std;
void Square (int &x,int &y);
void Cube (int &x,int &y);
void Swap (int &x,int &y);
void ChangeValues (int &x,int &y);
void TwoStrings (string &x,string &y);
void DisplayValues (int,int);
void Example4();
void DisplayValuesWithFunctionPointer(void (*) (int &,int &),int &,int &);
int num1;
int num2;
const int arraySize=4;
char choice[10];
void (*AfunctionPointer1)(int &,int &);
int main()
{
Example4();
cout<<"\n\n\tExiting.....\n\n\t";
return 0;
}
void DisplayValues(int x,int y){
cout<<"\tx: "<<x<<endl<<"\ty: "<<y<<endl;
}
void TwoStrings (string &x,string &y){
cout<<"\n\tstring 1 = "<<x<<"\n\tstring 2 = "<<y;
}
void Square (int &rx,int &ry){
rx*=rx;
ry*=ry;
}
void Cube (int &rx,int &ry){
int temp=rx;
rx*=rx;
rx=rx *temp;
temp=ry;
ry*=ry;
ry=ry *temp;
}
void Swap (int &rx,int &ry){
int temp=rx;
rx=ry;
ry=temp;
}
void ChangeValues (int &rx,int &ry){
char choice[10]="";
cout<<"\n\tnew value for num1: ";
cin>>choice;
if(!isdigit(choice[0])){
choice[0]='1';}
rx=atoi(choice);
cout<<"\n\tnew value for num2: ";
cin>>choice;
if(!isdigit(choice[0])){
choice[0]='1';
}
ry=atoi(choice);
}
void Example4(){
num1=3;
num2=9;
cout<<"\n\tExample 4 is on autopilot. We will use an array of function.";
cout<<"\n\tPointers to call each function as we iterate in a for() loop:\n";
for (int x=0;x<arraySize;x++){
switch(x){
case '0' : AfunctionPointer1=ChangeValues;break;
case '1' : AfunctionPointer1=Square;break;
case '2' : AfunctionPointer1=Cube;break;
case '3' : AfunctionPointer1=Swap;break;
default : cout<<"\n\tInvalid choice";break;
}
cout<<"\n\nLoop iteration # "<<x+1<<": ";
cout<<"\n\n----------------------------------------";
DisplayValuesWithFunctionPointer(AfunctionPointer1,num1,num2);
cout<<"\n\n----------------------------------------";
system("pause");
system("cls");
}
}
void DisplayValuesWithFunctionPointer(void (*functionPointer)(int &,int &),int & x,int & y){
cout<<"\n\nBefore:\n x = "<<x<<endl<<" y = "<<y<<endl;
functionPointer(x,y);
cout<<"\n\nAfter:\n x = "<<x<<endl<<" y = "<<y<<endl;
}
|