我正在製作一個菜單欄,它接受菜單項。我想要包含菜單欄的窗口來決定菜單項的行爲。所以我希望窗口將一個函數傳遞給菜單項。在一個類的成員中保存一個函數指針
我最好的嘗試讓我這個錯誤:
error: no matching function for call to 'MenuItem::setBehaviour(void (MyWindow::*)())'
這裏是MenuItem.h:
class MenuItem{
public:
typedef void (sf::RenderWindow::*function_type)();
MenuItem(sf::RenderWindow* win); // window that holds the menu bar
void setBehaviour(function_type f); // I want to be able to change the behaviour
// to reuse the menu item
void action(); // use the function
private:
sf::RenderWindow* m_window;
function_type m_function;
};
MenuItem.cpp
MenuItem::MenuItem(sf::RenderWindow* win) : m_window(win)
{
//ctor
}
void MenuItem::setBehaviour(function_type f)
{
m_function = f;
}
void MenuItem::action()
{
(m_window->*m_function)();
}
,增加了菜單欄上的窗口:
class MyWindow : public sf::RenderWindow
{
//...
void close();
};
和窗口的CPP文件:
MyWindow::MyWindow() : sf::RenderWindow(...)
{
//...
MenuItem item(this);
item.setBehaviour(&MyWindow::close); // error!
//...
}
//...
void MyWindow::close()
{
this->close();
}
嗯,你嘗試過沒有的'SF :: RenderWindow'成員,但來自派生類的函數指針。 –
啊...我直到現在纔看到您的評論。謝謝,那就是訣竅。 – MrMxyztplk