对于
Windows,Mac和iOS,以下代码编译时没有警告:
class MyClass { SomeOtherClass * m_object; void (SomeOtherClass::*m_callback)(); public: MyClass(SomeOtherClass * _object,void (SomeOtherClass::*_callback)()=NULL) : m_object(_object),m_callback(_callback) {} void DoStuff() { //generates warning: NULL used in arithmetic when compiling with the Android NDK if (NULL==m_callback) { m_object->DoNormalCallback(); } else { (m_object->*m_callback)(); } } };
为什么会产生警告,我该怎么办呢?
解决方法
我不认为你可以将0(或NULL)与成员函数指针进行比较,特别是因为它们可能实际上不是指针(例如,当函数是虚函数时).
就个人而言,我会在没有比较的情况下重写if测试,例如:
void DoStuff() { if (m_callback) { (m_object->*m_callback)(); } else { m_object->DoNormalCallback(); } }
并且,对于奖励积分,在构造函数中执行此测试.
class MyClass { SomeOtherClass * m_object; void (SomeOtherClass::*m_callback)(); public: MyClass(SomeOtherClass * _object,m_callback(_callback) { // Use "DoNormalCallback" unless some other method is requested. if (!m_callback) { m_callback = &SomeOtherClass::DoNormalCallback; } } void DoStuff() { (m_object->*m_callback)(); } };