简体   繁体   中英

Call function through pointer to class member

In following code:

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;
}

What would be correct syntax to make bar::bar_function work?

This works in ideone :

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

It's all about having the right level of indirection. Since p_foo is a pointer to member, we need to dereference it before attempting to access it from this . At this point, you have the actual foo_member object, not a pointer to it, so you can call its foo_function by dot notation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM