简体   繁体   中英

error: cannot convert 'long unsigned int (A::*)()' to 'poFunc {aka long unsigned int (*)()}'

some library have code like this:

typedef unsigned long(*poFunc)();
poFunc T ;
//...

void setupA(poFunc exFunc)
{
    T = exFunc;
}

and I can use it like this:

unsigned long run()
{
    return 9929UL;
}

int main()
{
    setupA(run);
}

Now I need to group the functions in a class like this:

class A
{
    private:
        unsigned long run();
    public:
        void start ();
};

unsigned long A::run()
{
    return 9929UL;
}

void A::start ()
{
    setupA(&A::run);
}

int main()
{
    A _a;
    _a.start();
}

and I get this error:

error: cannot convert 'long unsigned int (A::*)()' to 'poFunc {aka long unsigned int (*)()}' for argument '1' to 'void setupA(poFunc)'

I found this issue similar to my problem,but I have no idea how to fix this.

Thanks.

Declare the A::run method as static .

The following compiles and executes correctly.

typedef unsigned long(*poFunc)();
poFunc T ;

void setupA(poFunc exFunc)
{
    T = exFunc;
}
class A{

    poFunc T ;
    private:
        static  unsigned long run();
    public:
        void start ();

};

unsigned long A::run()
{
    return 9929UL;
}

void A::start ()
{
    setupA(&A::run);
}

int main()
{
    A _a;
    _a.start();

    printf("END\n");
}

Hope this helps out.

You can introduce your class before defining your new type (function pointer) by statement typedef.

class A;
typedef unsigned long(A::*poFunc)();

In typedef statement then you have to make clear that you want to point to a function that is defined in your class.

But I am not sure that this a good style of programming. You avoid the concept of classes. With your function pointer you are able to call a function that is declared as private from outside the class!

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