简体   繁体   English

错误:无法将'long unsigned int(A :: *)()'转换为'poFunc {aka long unsigned int(*)()}'

[英]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 . A :: run方法声明为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. 您可以在通过语句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. 在typedef语句中,您必须明确指出要指向类中定义的函数。

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! 使用函数指针,您可以调用从类外部声明为私有的函数!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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