简体   繁体   English

这是什么意思:警告:从'void(ClassName :: *)()'转换为'void(*)()'

[英]What does this mean: warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

I have a member function in a class that has a callback, but the callback isn't strictly neccessary, so it has a default callback, which is empty. 我在具有回调的类中有一个成员函数,但严格来说回调不是必需的,因此它具有默认的回调,该回调为空。 It seems to work fine, but I get an annoying warning: 似乎工作正常,但我得到一个烦人的警告:

warning: converting from ‘void (ClassName::*)()’ to ‘void (*)()’

I'm trying to figure out what it means and how to turn it off (or fix it if I really am doing something wrong). 我试图弄清楚它的含义以及如何将其关闭(如果我确实做错了,请修复它)。 Here's some simple code: 这是一些简单的代码:

class ClassName{
public:
    void doSomething(void (*callbackFunction)() = (void(*)()) &ClassName::doNothing){
        callbackFunction();
    }
    void doNothing(){}
};

int main(){
    ClassName x;
    x.doSomething();
    return 0;
}

Note: If I do this (without explicitly casting it as a void(*)() ): 注意:如果我这样做(没有显式将其强制转换为void(*)() ):

void doSomething(void (*callbackFunction)() = &ClassName::doNothing)

I get this: 我明白了:

main.cpp:3: error: default argument for parameter of type ‘void (*)()’ has type ‘void (ClassName::*)()’

The issue is that you're passing a pointer to an instance method rather than a static method. 问题是您要传递指向实例方法而不是静态方法的指针。 If you make doNothing a static method (which means no implicit instance argument), the warning goes away. 如果将doNothing静态方法(这意味着没有隐式实例参数),则警告将消失。

Specifically, 特别,

 warning: converting from 'void (ClassName::*)()' to 'void (*)()' 

exactly is saying that it's converting from a member function of class ClassName, to a non-member function. 确切地说,它是从ClassName类的成员函数转换为非成员函数。

See also the C++ FAQ Lite entry about pointers to member functions and pointers to functions . 另请参见有关成员函数的指针和函数的指针的C ++ FAQ Lite 条目

Free function pointer is not the same as class member function pointer, which requires an instance of the class at call site. 自由函数指针与类成员函数指针不同,后者需要在调用站点上获得该类的实例。 Though a static member function will do. 虽然可以使用静态成员函数。

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

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