[英]how to pass a void function to a void pointer in C++
這是我的問題:我有我的 tact 類,用於嵌入式應用程序中的觸覺按鈕。
我添加了 setFunctions() 函數,以便我可以將 3 個函數鏈接到我創建的每個 tact 實例(它將處理短按鈕按下、釋放和長按)。
class tact
{
public:
tact(int assigned_pin, input_shift_register shift = {0,0,0}); // Constructor
void debounce();
short poll(bool debounce_flag);
void activate();
void setFunctions(void short_press_function(void), void release_press_function(void), void long_press_function(void));
short state;
private:
int pin;
void (*short_ptr)(void);
void (*release_ptr)(void);
void (*long_ptr)(void);
}
因此,我可以在 main 中為我需要的每個 tact 實例創建 3 個獨特的函數,並使用 setFunctions() 成員將它們鏈接到 tact 實例。
這就是 setFunctions 成員的工作方式(或應該這樣做)。 它將 3 個獨特的函數鏈接到 3 個 void 指針,它們是私有下的 tact 類的一部分:
void tact::setFunctions(void short_press_function(), void release_press_function(), void long_press_function())
{
short_ptr = short_press_function;
release_ptr = release_press_function;
long_ptr = long_press_function;
}
然后,指針用於訪問來自 activate 成員的功能(一個簡單的開關案例,用於查看輕觸按鈕當前處於哪種狀態):
void tact::activate()
{
switch (tact::state)
{
case SHORT_EFFECT_REQUIRED:
short_ptr();
break;
case RELEASE_EFFECT_REQUIRED:
release_ptr();
break;
case LONG_EFFECT_REQUIRED:
long_ptr();
break;
default:
break;
}
tact::state = 0;
}
總的來說,我打算這樣做:
void up_short()
{
}
void up_release()
{
}
void up_long()
{
}
tact upPin(2);
void setup()
{
upPin.setFunctions(up_short(), up_release(), up_long()); //ERRORS ARE HERE!!
}
void loop()
{
//use the tact buttons in my applications!
upPin.poll(DEBOUNCED); // Updates upPin.state
if(upPin.state) //if not 0, either pressed, released, or pressed long enough
upPin.activate();
}
但是 setFunctions() 提到了 3 次相同的錯誤:
argument of type "void" is incompatible with parameter of type "void (*)()"
我作為參數傳遞給 setFunctions() 的 3 個函數中的每一個都有一個錯誤
所以我的問題是我做錯了什么? 我真的很喜歡如何簡單地使用 upPin.activate 來訪問我的函數,而正確的函數是自動完成的。我不明白為什么 setFunctions() 不讓我將 void 函數鏈接到我的 void 函數指針???
謝謝!
線路:
upPin.setFunctions(up_short(), up_release(), up_long())
分別調用up_short()
、 up_release()
和up_long()
函數。 這些函數返回void
,然后將其傳遞給setFunctions
每個參數 - 這就是您遇到此錯誤 3 次的原因。
您想要做的是將(指向)函數本身傳遞給setFunctions
如果您將行更改為:
upPin.setFunctions(up_short, up_release, up_long);
你應該看到這個作品
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.