Re: pointers to functions
somelawsbelongtoyou@gmail.com wrote:
Hello all,
I need some help. I've been learning C++ using the tutorial at
Cplusplus.com (http://www.cplusplus.com/doc/tutorial/pointers.html is
the page in question). Near the bottom of the section on pointers,
there is a code sample which is supposed to be demonstrating using
pointers to point to functions. It didn't seem to make sense, so I
tried compiling it; it wouldn't compile! Since the author of the
tutorial didn't leave any contact information, I'm turning to you
folks. Can anyone correct the following code for me?
#include <iostream>
using namespace std;
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
int minus (int,int) = subtraction;
int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}
int main ()
{
int m,n;
m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}
Thanks for your help,
Danny
p.s. The compile errors state that "function `int minus(int, int)' is
initialized like a variable" and "`minus' undeclared (first use this
function)".
What about something like this....
#include <iostream>
//yuck! using namespace std;
int addition (int a, int b)
{ return (a+b); }
int subtraction (int a, int b)
{ return (a-b); }
//int minus (int,int) = subtraction;
typedef int(op)(int,int);
op * minus = subtraction;
int operation (int x, int y, int (*functocall)(int,int))
{
int g;
g = (*functocall)(x,y);
return (g);
}
int main ()
{
int m,n;
m = operation (7, 5, addition);
n = operation (20, m, minus);
std::cout <<n;
return 0;
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]