2012-10-07 80 views
2

我有一個Button類:C++:類具有指針功能屬性

class Button : public Component { 

private: 
    SDL_Rect box; 
    void* function; 

public: 
    Button(int x, int y, int w, int h, void (*function)()); 
    ~Button(); 
    void handleEvents(SDL_Event event); 

}; 

而且我要在方法Button::handleEvents執行Button::function

void Button::handleEvents(SDL_Event event) { 
    int x = 0, y = 0; 
    // If user clicked mouse 
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) { 
      // Get mouse offsets 
      x = event.button.x; 
      y = event.button.y; 

      // If mouse inside button 
      if((x > box.x) && (x < box.x + box.w) && (y > box.y) && (y < box.y + box.h)) 
      { 
       this->function(); 
       return; 
      } 
    } 

} 

當我嘗試編譯,我得到以下錯誤:

Button.cpp: In the constructor ‘Button::Button(int, int, int, int, void (*)(), std::string)’: 
Button.cpp:17:18: error: invalid conversion from ‘void (*)()’ to ‘void*’ [-fpermissive] 
Button.cpp: In the function ‘virtual void Button::handleEvents(SDL_Event)’: 
Button.cpp:45:19: error: can't use ‘((Button*)this)->Button::function’ as a function 

回答

2

在您的私人部分的函數指針沒有聲明,因爲它應該是。

它應該是:

void *(functionPtr)(); 

this問題的更多信息。

+0

當我從類「按鈕」消滅的對象,我應該做的與指針的東西嗎? –

+0

我不明白你的問題。你能澄清一下嗎? – 2012-10-08 07:21:46

1

在你的類變量聲明,你有

void* function; 

聲明一個名爲function變量,它是一個指向void。聲明它作爲一個函數指針,你需要相同的語法,在您的參數列表:

void (*function)(); 

現在,這是一個指向返回void的功能。

0

你可能會改變字段聲明,

void * function; // a void ptr 
void (*function)(); // a ptr to function with signature `void()` 

或使用強制:

((void (*)())this->function)(); 
1

我建議std::function<void()>對於這種目的:

#include <functional> 

class Button : public Component 
{ 
private: 
    SDL_Rect box; 
    std::function<void()> function; 

public: 
    Button(int x, int y, int w, int h, std::function<void()> f); 
    ~Button(); 
    void handleEvents(SDL_Event event); 
}; 

void Button::handleEvents(SDL_Event event) 
{ 
    int x = 0, y = 0; 
    // If user clicked mouse 
    if(event.type == SDL_MOUSEBUTTONDOWN && event.button.button == SDL_BUTTON_LEFT) 
    { 
     // Get mouse offsets 
     x = event.button.x; 
     y = event.button.y; 
     // If mouse inside button 
     if((x > box.x) && (x < box.x + box.w) && (y > box.y) && (y < box.y + box.h)) 
     { 
      function(); 
      return; 
     } 
    } 
}