禁用“错误函数转换”警告 [英] Disabling "bad function cast" warning
问题描述
我收到以下警告:
warning: converting from 'void (MyClass::*)(byte)' to 'void (*)(byte)'
这是因为我需要传递作为参数a成员函数而不是普通函数。但是程序运行正常。
This is because I need to pass as argument a member function instead of an ordinary function. But the program is running correctly.
我想禁用此警告(Wno-bad-function-cast不适用于C ++)或实现不同的
I'd like to disable this warning (Wno-bad-function-cast doesn't work for C++) or to implement a different way to pass a member function.
推荐答案
否。认真对待这个警告。
No. Take this warning seriously. You should rather change your code to handle this scenario.
指向成员函数的指针( void(MyClass :: *)(byte)
)和正常函数指针( void(*)(byte)
)完全不同。 请参阅此链接。你不能像这样施放他们。
Pointer to member function(void (MyClass::*)(byte)
) and normal function pointer (void (*)(byte)
) are entirely different. See this link. You cannot cast them just like that. It results in undefined behavior or crash.
看到这里,它们是如何不同:
See here, how they are different:
void foo (byte); // normal function
struct MyClass {
void foo (byte); // member function
}
现在你可能会觉得 foo(byte)
和 MyClass :: foo(byte)
有相同的签名,那么为什么他们的函数指针不相同。这是因为 MyClass :: foo(byte)
在某种程度上被内部解析为,
Now you may feel that, foo(byte)
and MyClass::foo(byte)
have same signature, then why their function pointers are NOT same. It's because, MyClass::foo(byte)
is internally resolved somewhat as,
void foo(MyClass* const this, byte);
现在你可以闻到它们之间的区别。
Now you can smell the difference between them.
将成员函数的指针声明为
Declare pointer to member function as,
void (MyClass::*ptr)(byte) = &MyClass::foo;
您必须使用 ptr
对象 MyClass
,例如:
You have to use this ptr
with the object of MyClass
, such as:
MyClass obj;
obj.*ptr('a');
这篇关于禁用“错误函数转换”警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!