2012-03-09 195 views
1

嗨,我想在C/C++中學習一些函數指針,並試圖在Ubuntu上使用gcc編寫下面的C++代碼。通過引用傳遞函數指針

此代碼應執行編譯

#include <iostream> 
#include <iomanip> 
//Adds two numbers 
int add(int a, int b) 
{ 
    return a+b; 
} 
//Multiplies two numbers 
int multiply(int a, int b) 
{ 
    return a*b; 
} 

//Function to set the correct function to be executed. 
//All functions here should have the same signature. 
void functionsetter(void (*ptr2fun)(int,int) ) 
{ 
#ifdef ADD 
    ptr2fun = add; 
#endif 

#ifdef MULTIPLY 
    ptr2fun = multiply 
#endif 
} 

int main(int argc, char *argv[]) 
{ 
    int a = 5; 
    int b = 6; 

    void (*foo)(int,int); 
    functionsetter(foo); 

    return 0; 
} 

期間提供的乘法或或取決於 預處理標誌add函數-DADD或-DMULTIPLY我無法弄清楚如何函數指針foo傳遞給function-setter功能通過參考。有人可以幫我解決這個問題。我確信

functionsetter是錯誤的代碼,請讓我知道如何解決它。

我試圖用g++ -O2 -g -Wall -DADD main.cpp -o main

注意編譯:我想在其他一些代碼來使用這些預處理器標誌和函數指針別處。 請讓我知道這樣的事情是一個好主意/實踐。

回答

5

使用typedef

typedef void (*MyFunctionPointer)(int,int); 
void functionsetter(MyFunctionPointer& fp); 

我想一些其他的代碼使用這些預處理器標誌和函數指針別處。請讓我知道這樣的事情是不是一個好主意/實踐。

不,不是真的。從你的例子中不清楚你想要完成什麼,但是你的實現很不尋常。考慮使用虛擬成員函數或std::function在運行時切換函數實現,或者(可能)使用模板在編譯時切換它們。使用條件編譯進行靜態選擇沒有任何問題,但將它與函數指針混合有點奇怪。

沒有很好地理解你要解決的問題,很難就如何最好地解決問題給出好的建議。

1

你會簽名改爲:

void functionsetter(void (*&ptr2fun)(int,int) ) 

注意,ptr2fun函數指針的簽名錯誤,你的增加和乘函數返回一個int,所以必須ptr2fun

這將成爲一個很容易,如果你使用typedef:

typedef int (*ptr2fun)(int,int); 
void functionsetter(ptr2fun& func) { ... 

雖然,個人我只是返回函數指針。

ptr2fun functionsetter() 
{ 
#ifdef ADD 
    return add; 
#endif 

#ifdef MULTIPLY 
    return multiply 
#endif 
} 
1

首先,你不能傳遞一個函數指針參考的方法,你只是傳遞一個函數指針。您需要將方法簽名更改爲

void functionsetter(void (*&ptr2fun)(int,int) ) 

而且,你的方法簽名是在一些地方void(*)(int,int)int(*)(int,int)一些,他們也許應該是無處不在後者,因爲您的加載和繁殖方法返回int。這就是說,由於您使用的是C++,因此我不推薦使用這種方式來操作指針,C++具有繼承/虛擬方法,通常可以取代大多數函數指針的使用,並使代碼更具可讀性,可擴展性。

9

,不使用typedef,對於一個函數指針引用的語法是:

void functionsetter(void (*&ptr2fun)(int, int)) { ... } 

但一般簡單的創建指針類型typedef

typedef void (*FunctionPointer)(int, int); 

void functionsetter(FunctionPointer& ptr2fun) { ... } 

或爲功能類型:

typedef void Function(int, int); 

void functionsetter(Function*& ptr2fun) { ... }