通过指向 class 成员的指针调用函数

Call function through pointer to class member

在下面的代码中:

class foo
{
public:
    void foo_function() {};
};

class bar
{
public:
    foo foo_member;

    void bar_function(foo bar::*p_foo)
    {
        // what is the corrct sintax for following:
        this->*p_foo->foo_function(); // expression must have a pointer type??
    }
};


int main()
{
    foo foo_obj;
    bar bar_obj;
    typedef foo bar::*p_foo;
    p_foo blah = &bar::foo_member;
    bar_obj.bar_function(blah);
    return 0;
}

使 bar::bar_function 工作的正确语法是什么?

这适用于 ideone:

void bar_function(foo bar::*p_foo)
{
    (this->*p_foo).foo_function();
}

关键在于拥有正确的间接级别。由于 p_foo 是指向成员的指针,我们需要在尝试从 this 访问它之前取消引用它。此时,您拥有实际的 foo_member 对象,而不是指向它的指针,因此您可以通过点符号调用它的 foo_function