简体   繁体   中英

Abstract function pointer doesn't work

I'm having this code for a GUI design for a mbed microcontroller:

This is my abstract class Widget.h with different subclasses like Button or Fader (not sure I can add variables this way in a abstract class but it compiles.

class Layout; //incomplete type

class Widget {    
    public:
        virtual void display(int x, int y) = 0; //pure virtual function for displaying the object
        virtual bool touchEvent(int x, int y)= 0;  //pure virtual function for checking if the touch does something for the widget
        void (*function)();
        Layout *layout;
};

Now I want to call the function pointer that I created

 if(currentWidget->function != NULL){
                    (currentWidget->function)(); 
 }

But the program stops here. I also want to change the activeLayout like this, but it also doesn't work.

if(currentWidget->layout != NULL){
                    Layout *templayout = currentWidget->layout;
                    activeLayout = templayout;
}

Am I this wrong in my approach in this? How could I fix it?

Yoo should assign a NULL value to function , for example in the constructor, to make the test if(currentWidget->layout != NULL) meaningful, if you don't, function will point to some garbage, the test would pass and you will execute into garbage, causing a GPF in the best case. Then, by a design point of view, why are you using a raw function pointer? Such things should be handled with polymorphism instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM