我一直在網上尋找一段時間,而且還沒有發現任何與我的問題完全相同的內容。我使用了這個東西定義一個類:如何在C/C++中將typedef函數作爲參數傳遞
typedef bool ProgressCallback(double progress);
有那麼使用這個像這樣的功能:
// The documentation says that it will call progress_callback()
// during the write where the progress parameter = percentage complete
void WriteToFile(char* filename, ProgressCallback* progress_callback)
正是我怎樣調用這個函數?這主要是typedef語法引起了我的注意,因爲通常將函數作爲參數傳遞並不是那麼困難。這是我嘗試雖然:
// Apparently I can't just say "Progress Callback MyCallback{}"
// Since it gives me "function type may not come from a typedef" error
bool MyCallbackFunction(double progress){
return true;
}
void OtherFunction(){
// Can't assign. I get "a value type of bool (*)(double progress)" cannot be
// used to initalize an entity of type ProgressCallback*" error.
ProgressCallback* myfunction = MyCallbackFunction;
WriteToFile("Test.txt", myfunction);
}
很明顯,我知道我這樣做是不正確的。但這是我得到的最接近的。我完全不知道我應該如何將該參數傳遞給WriteToFile()。
任何幫助將不勝感激!
C沒有類。 – melpomene
typedef只是將一個標識符聲明爲一個類型的別名。在這種情況下,該類型是特定的函數類型,並且您正在將指針傳遞給該類型的函數。您可以通過取消引用指針來調用指向函數來獲取函數指示符,然後用它形成一個函數調用表達式:'(* progress_callback)(0.5)'。 –
[無法重現](http://coliru.stacked-crooked.com/a/cfb3cb3a017f5269)。請提供[mcve]。 – Angew