我要问一些具体的问题。
有关问题号码2这里是我的意思是:
无效S(无效){ // ...}无效F(功能){//我应该把类型为传递函数作为参数 // ...}F(S);解决方案
要定义一个函数指针,请使用以下语法:
return_type(* ref_name)(类型ARGS,...)因此,要定义一个名为DoSomething的函数引用,它返回一个 INT ,并采取在 INT 参数,你会这样写:
INT(* DoSomething的)(INT号);然后,您可以参考分配到这样一个实际的功能:
INT someFunction(int参数){ 的printf(%i上的说法);}DoSomething的=安培; someFunction;一旦这样做了,你可以然后直接调用它:
DoSomething的(5); //输出5由于函数指针基本上只是指针,你的确可以在你的类使用它们作为实例变量。
在接受函数指针作为参数,我preFER使用的的typedef 而不是在函数原型使用混乱的语法:
的typedef INT(* FunctionAcceptingAndReturningInt)(int参数);您可以使用这个新定义的类型作为函数的参数的类型:
无效invokeFunction(INT func_argument,FunctionAcceptingAndReturningInt FUNC){ INT结果= FUNC(func_argument); 的printf(%i的,结果);}INT timesFive(INT ARG){ 返回ARG * 5;}invokeFunction(10,&安培; timesFive); //输出50I'm asking some specific questions.
For question number 2 here is what I mean:
void s(void) { //... } void f(function) { // what should I put as type to pass a function as an argument //... } f(s);解决方案
To define a function pointer, use the following syntax:
return_type (*ref_name) (type args, ...)So, to define a function reference named "doSomething", which returns an int and takes in an int argument, you'd write this:
int (*doSomething)(int number);You can then assign the reference to an actual function like this:
int someFunction(int argument) { printf("%i", argument); } doSomething = &someFunction;Once that's done, you can then invoke it directly:
doSomething(5); //prints 5Because function pointers are essentially just pointers, you can indeed use them as instance variables in your classes.
When accepting function pointers as arguments, I prefer to use a typedef instead of using the cluttered syntax in the function prototype:
typedef int (*FunctionAcceptingAndReturningInt)(int argument);You can then use this newly defined type as the type of the argument for the function:
void invokeFunction(int func_argument, FunctionAcceptingAndReturningInt func) { int result = func(func_argument); printf("%i", result); } int timesFive(int arg) { return arg * 5; } invokeFunction(10, ×Five); //prints 50
更多推荐
如何函数指针的工作?
发布评论