函数指针错误

Jon*_*ony 0 c++ pointers function

这个简单的代码可以帮助我吗?

#include <iostream>
using namespace std;

void testFunction(){
    cout<<"This is the test function 0"<<endl;
}

void testFunction1(){
    cout<<"This is the test function 1"<<endl;
}

void testFunction2(){
    cout<<"This is the test function 2"<<endl;
}

void (*fp[])()={testFunction,testFunction1,testFunction2};

int main(){

    //fp=testFunction;
    (*fp[testFunction1])();
    //cout<<"Addrees of the function pointer is:"<<*fp;
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

error: invalid types `void (*[3])()[void ()()]' for array subscript|
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 7

您正在尝试将函数指针用作数组索引.那不会飞,数组索引必须是整数.

要通过函数指针调用,只需调用:

(*fp[1])();
Run Code Online (Sandbox Code Playgroud)

或者(甚至更短!)

fp[1]();
Run Code Online (Sandbox Code Playgroud)

将工作.