简体   繁体   English

C ++函数指针

[英]C++ Pointers to functions

using namespace std;

int addition (int a, int b)
{
    return (a+b);
}

int subtraction (int a, int b)
{
    return (a-b);
}
int operation (int x, int y, int (*functocall)(int,int))
{
    int g;
    g = (*functocall)(x,y);
    return(g);
}
int main()
{
    int m,n;
    int (*minus)(int,int) = subtraction;

    m = operation (7,5,addition);
    n = operation (20,m,minus);
    cout << n;
    return 0;
}

Can anybody explain this line for me 谁能为我解释这句话

int (*minus)(int,int) = subtraction;

Thanks a lot! 非常感谢!

int (*minus)(int,int) = subtraction; int(*减)(int,int)=减法; is creating a variable called minus and assigning it a pointer to the function called subtraction . 正在创建一个名为减号的变量,并为其分配一个指向减法函数的指针。 if the code is valid then the function subtraction would be declared int subtraction(int a, int b); 如果代码有效,则将函数减法声明为int subtraction(int a,int b); .

the best way to deal with function pointers is to make them readable using typedef. 处理函数指针的最好方法是使用typedef使它们可读。

example: 例:

typedef int (*math_op)(int,int); // new types is math_op

int subtraction (int a, int b)
{
    return (a-b);
}

math_op minus = subtraction;

later on these can be called like they are normal functions. 以后可以像正常功能一样调用它们。

example: 例:

int result = minus(10, 2); // result is now set to 8

your code rewritten: 您的代码被重写:

using namespace std;

typedef int (*math_op)(int,int); // new types is math_op

int addition (int a, int b)
{
    return (a+b);
}

int subtraction (int a, int b)
{
    return (a-b);
}

int operation (int x, int y, math_op functocall)
{
    int g;
    g = functocall(x,y);
    return(g);
}

int main()
{
    int m,n;
    math_op minus = subtraction;

    m = operation (7,5,addition);
    n = operation (20,m,minus);
    cout << n;
    return 0;
}
int (*minus)(int,int)

says

A pointer to a function taking two ints as arguments returning an int. 指向以两个int作为参数返回int的函数的指针。

The parentheses around (*minus) are there to make sure that the asterisk binds to the name of the typedef and not the return type (ie, the function does not return an int*). 此处的括号(*minus)可以确保星号绑定到typedef的名称,而不是返回类型(即该函数不返回int *)。

"minus" is a name of a variable which is a pointer to a function taking two int arguments and returning another int. “减号”是变量的名称,它是指向带有两个int参数并返回另一个int的函数的指针。 The function called "operation" takes 3 arguments: 2 ints and a pointer to a function which operates on 2 ints and return another one. 称为“操作”的函数带有3个参数:2个整数和指向对该2个整数进行运算并返回另一个整数的函数的指针。 When invoked, the operation function applies argument 3 to the arguments 1 and 2. 调用时,操作函数将参数3应用于参数1和2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM