简体   繁体   中英

Code replaced by compiler for Function pointers of member functions

It has been really hard for me to understand function pointers call with respect to member functions in the following example.

(f.*(FPTR) bp)(0); // This call b()
 (b.*(BPTR) fp)(0); // This call f()

I would like to know the code replaced (as I know a function call like obj.Fun() is replaced by Fun(&obj) by the compiler for these two function calls when those member functions are virtual and non-virtual. Anyone help me to understand, Please ?

I want to understand more like this link explanation: http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/

#include <iostream>

using std::cout;
using std::endl;

class Foo
{
public:
    void f(int i = 0)
    {
        cout << "Foo" << endl;

    }
};

class Bar
{
public:
    void b(char c = 'b')
    {
        cout << "Bar" << endl;
    }
};


int main()
{
    typedef void (Foo::*FPTR) (int);
    typedef void (Bar::*BPTR) (char);

    FPTR fp = &Foo::f;
    BPTR bp = &Bar::b;

    Foo f;
    Bar b;

    /* 
     * we are casting pointer to non-compatible type here 
     * Code works, but want to know how it is.
     */
    (f.*(FPTR) bp)(0);
    (b.*(BPTR) fp)(0);


    return 0;
}

Thanks

您的代码显示未定义的行为 ,这意味着编译器可以执行其喜欢的任何操作, 包括您 (错误地) 期望它执行的操作。

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