Function pointers
Here's a brief example of how to do function pointers in C++ and C#.
The functionality is the same in both examples: either the minimum or the maximum of two numbers is returned by MinOrMax, depending on a bool that is passed in along with the int's.
C++
int Min(int a,int b);
int Max(int a,int b);
int MinOrMax(int a, int b, bool findMin);
int Min(int a, int b)
{
return (a < b) ? a : b;
}
int Max(int a, int b)
{
return (a > b) ? a : b;
}
int MinOrMax(int a, int b, bool findMin)
{
int (*MIN_MAX)(int,int);
if (findMin)
{
MIN_MAX = &Min;
}
else
{
MIN_MAX = &Max;
}
int ret = (*MIN_MAX)(a, b);
return ret;
}
int main()
{
cout<<"Min(1,2) = "<<MinOrMax(1, 2, true)<<endl;
cout<<"Max(1,2) = "<<MinOrMax(1, 2, false)<<endl;
return 0;
}
C#
delegate int MIN_MAX(int a, int b);
static int MinOrMax(int a, int b, bool findMin)
{
MIN_MAX v;
if (findMin)
{
v = new MIN_MAX(Min);
}
else
{
v = new MIN_MAX(Max);
}
int ret = v(a,b);
return ret;
}
static int Min(int a, int b)
{
return (a < b) ? a : b
}
static int Max(int a, int b)
{
return (a > b) ? a : b;
}
static void Main()
{
MessageBox.Show("Min(1,2) = " +
MinOrMax(1, 2, true));
MessageBox.Show("Max(1,2) = " +
MinOrMax(1, 2, false));
}
No comments:
Post a Comment