C ++ class element pointer for global function

I want to have a class that has a function pointer as a member

here's the function pointer:

typedef double (*Function)(double); 

here is a function that matches the definition of a function pointer:

 double f1(double x) { return 0; } 

here is the class definition:

 class IntegrFunction { public: Function* function; }; 

and somewhere in the main function I want to do something like this:

 IntegrFunction func1; func1.function = f1; 

But this code does not work.

Can a class member be assigned a function pointer to a global function declared as described above? Or do I need to change something in the definition of a function pointer?

Thanks,

+6
source share
5 answers

Replace this:

 class IntegrFunction { public: Function* function; }; 

with this:

 class IntegrFunction { public: Function function; }; 

Your typedef is already creating a function pointer. A Function* function declaration creates a pointer to a function pointer.

+9
source

Just replace

 Function* function; 

to

 Function function; 
+4
source

You declare the variable as Function* function , but the Function typedef is already a typedef for the pointer. Thus, the type of the function pointer is Function (without *).

+2
source

Replace

 typedef double (*Function)(double); 

by

 typedef double Function(double); 

to enter the type of function. Then you can record * when using it.

0
source

You need to use the address operator to get a pointer to a function in standard C ++ 03.

 func1.function = &f1; 
-3
source

Source: https://habr.com/ru/post/888130/


All Articles