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

时间:2017-02-22 16:41:10

标签: c++ pointer-to-member

我在从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)();
}

0 个答案:

没有答案