One question about function definition in C++ -
i'm reading material function pointer in c++, , come across 1 function definition not understand.
standard function definition have form:
type name (param...)
but following definition seems little strange me. can explain me ? thanks.
float (*getptr1(const char opcode)) (float, float)<br> { if(opcode == '+') return + else return − // default if invalid operator passed }
note: plus , minus 2 functions param (float, float) , return float.
the rule reading hairy declarations start leftmost identifier , work way out, remembering ()
, []
bind before *
(i.e., *a[]
array of pointers, (*a)[]
pointer array, *f()
function returning pointer, , (*f)()
pointer function):
getptr1 -- getptr1 getptr1( ) -- function getptr1( opcode) -- taking single parameter named opcode getptr1(const char opcode) -- of type const char *getptr1(const char opcode) -- , returning pointer (*getptr1(const char opcode)) ( ) -- function (*getptr1(const char opcode)) (float, float) -- taking 2 parameters of type float float (*getptr1(const char opcode)) (float, float) -- , returning float
so, if opcode
equal '+', getptr1
return pointer function plus
, , if it's '-', return pointer function minus
.
c , c++ declaration syntax expression-centric (much bjarne pretend otherwise); form of declaration should match form of expression used in code.
if have function f
returns pointer int
, want access value being pointed to, execute function , dereference result:
x = *f();
the type of expression *f()
int
, declaration/definition function is
int *f() { ... }
now suppose have function f1
returns pointer function f
defined above, , want access integer value calling f1
. need call f1
, derefence result (which function f
), , execute it, , dereference that result (since f
returns pointer):
x = *(*f1())(); // *f1() == f, (*f1())() == f() , *(*f1())() == *f()
the type of expression *(*f1())()
int
, decaration/definition f1
needs be
int *(*f1())() { return f; }
Comments
Post a Comment