2010-03-31 102 views
0

任何人都可以幫助我這個簡單的代碼?函數指針錯誤

#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; 
} 

我收到以下錯誤:

error: invalid types `void (*[3])()[void()()]' for array subscript| 
+1

那可真是邪的東西,順便說一句。 – 2010-03-31 08:46:36

回答

7

你正在嘗試使用函數指針作爲數組索引。這不會飛,數組索引必須是整數。

要通過函數指針調用,只要致電:

(*fp[1])(); 

fp[1](); 

將工作(甚至更短!)。

+0

謝謝......我不知道我是如何錯過的。 – Jony 2010-03-31 08:47:18

2

我想你的意思是寫:

(*fp[1])(); 

也就是說,你的索引數組與一個int,而不是函數本身。

2

你的索引功能的陣列fp用一個函數指針,你可以試試:

(*fp[some_index])(); 

代替