gpt4 book ai didi

c++ - 无法从静态方法调用指向成员函数的指针

转载 作者:可可西里 更新时间:2023-11-01 17:38:55 25 4
gpt4 key购买 nike

我在调用从 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 是非静态数据成员,因此您不能从静态函数访问它。

如果你想引用tfunction,你可以这样做:

        (t->*(t->function))();

关于c++ - 无法从静态方法调用指向成员函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42397341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com