指向函数的指针

Dev*_*no1 4 c++ pointers function-pointers

我有两个基本的Cpp任务,但我仍然遇到问题.首先是编写函数mul1,div1,sub1,sum1,将int作为参数并返回int.然后我需要为函数mul1和sum1创建指针ptrFun1和ptrFun2,并打印使用它们的结果.问题始于定义这些指针.我以为我做得对,但是devcpp在编译时给了我错误.

#include <iostream>
using namespace std;

int mul1(int a,int b)
{
    return a * b;
}

int div1(int a,int b)
{
    return a / b;    
}

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

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


int main()
{
    int a=1;
    int b=5;

    cout << mul1(a,b) << endl;
    cout << div1(a,b) << endl;
    cout << sum1(a,b) << endl;
    cout << sub1(a,b) << endl;

    int *funPtr1(int, int);
    int *funPtr2(int, int);

    funPtr1 = sum1;
    funPtr2 = mul1;

    cout << funPtr1(a,b) << endl;
    cout << funPtr2(a,b) << endl;

    system("PAUSE");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)
38 assignment of function `int* funPtr1(int, int)'
38 cannot convert `int ()(int, int)' to `int*()(int, int)' in assignment

任务2是创建指向名为tabFunPtr的函数的指针数组.怎么做 ?

CB *_*ley 15

而不是int *funPtr1(int, int)你需要int (*funPtr1)(int, int)声明一个函数指针.否则你只是声明一个返回指针的函数int.

对于函数指针数组,最好typedef为函数指针类型创建一个,然后使用该typedef声明数组.

例如

funPtr_type array_of_fn_ptrs[];
Run Code Online (Sandbox Code Playgroud)