C++:将指向函数的指针作为属性的类 [英] C++: class that has a pointer to a function as an attribute

查看:58
本文介绍了C++:将指向函数的指针作为属性的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Button类:

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

推荐答案

您的私有节中的函数指针未按应该的方式声明。

应该是:

void (*functionPtr)();

有关详细信息,请查看this问题。

这篇关于C++:将指向函数的指针作为属性的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆