无法从静态方法调用指向成员函数的指针
Cannot call pointer to member function from static method
我在调用从 void*
转换而来的对象上的成员函数指针时遇到困难。请参阅以下示例:
class Test
{
public:
Test(int pointTo)
{
if (pointTo == 1)
function = &Test::Function1;
else
function = &Test::Function2;
}
static void CallIt(void* cStyle)
{
Test* t(static_cast<Test*>(cStyle));
(t->*function)();// error C2568: '->*': unable to resolve function overload
}
void CallIt()
{
(this->*function)();// Works just fine
}
private:
typedef void (Test::*ptrToMemberFunc)();
ptrToMemberFunc function;
void Function1()
{
std::cout << "Function 1" << std::endl;
}
void Function2()
{
std::cout << "Function 2" << std::endl;
}
};
int main()
{
Test t1(1);
Test t2(2);
Test::CallIt(static_cast<void*>(&t1));
Test::CallIt(static_cast<void*>(&t2));
t1.CallIt();
t2.CallIt();
return 0;
}
将对象转换为 void*
并返回时会发生什么?为什么我不能再调用指向成员函数的指针?
编辑:
按如下方式修改CallIt()
可以让程序编译通过,但我还是很好奇为什么原来的不行
static void CallIt(void* cStyle)
{
Test* t(static_cast<Test*>(cStyle));
Test::ptrToMemberFunc pf(t->function);
(t->*pf)();
}
main.cpp:17:14: error: invalid use of member 'function' in static member function
(t->*function)();// error C2568: '->*': unable to resolve function overload
^~~~~~~~
function
是非静态数据成员,因此您不能从静态函数访问它。
如果你想引用t
的function
,你可以这样做:
(t->*(t->function))();
我在调用从 void*
转换而来的对象上的成员函数指针时遇到困难。请参阅以下示例:
class Test
{
public:
Test(int pointTo)
{
if (pointTo == 1)
function = &Test::Function1;
else
function = &Test::Function2;
}
static void CallIt(void* cStyle)
{
Test* t(static_cast<Test*>(cStyle));
(t->*function)();// error C2568: '->*': unable to resolve function overload
}
void CallIt()
{
(this->*function)();// Works just fine
}
private:
typedef void (Test::*ptrToMemberFunc)();
ptrToMemberFunc function;
void Function1()
{
std::cout << "Function 1" << std::endl;
}
void Function2()
{
std::cout << "Function 2" << std::endl;
}
};
int main()
{
Test t1(1);
Test t2(2);
Test::CallIt(static_cast<void*>(&t1));
Test::CallIt(static_cast<void*>(&t2));
t1.CallIt();
t2.CallIt();
return 0;
}
将对象转换为 void*
并返回时会发生什么?为什么我不能再调用指向成员函数的指针?
编辑:
按如下方式修改CallIt()
可以让程序编译通过,但我还是很好奇为什么原来的不行
static void CallIt(void* cStyle)
{
Test* t(static_cast<Test*>(cStyle));
Test::ptrToMemberFunc pf(t->function);
(t->*pf)();
}
main.cpp:17:14: error: invalid use of member 'function' in static member function
(t->*function)();// error C2568: '->*': unable to resolve function overload
^~~~~~~~
function
是非静态数据成员,因此您不能从静态函数访问它。
如果你想引用t
的function
,你可以这样做:
(t->*(t->function))();