代码由编译器代替,用于成员功能的功能指针

Code replaced by compiler for Function pointers of member functions

本文关键字:功能 成员 指针 用于 编译器 代码      更新时间:2023-10-16

我真的很难理解函数指针在以下示例中相对于成员函数。

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

我想知道替换的代码(众所周知,诸如obj.fun()之类的函数呼叫被娱乐替换(& obj)由编译器由这两个函数在这些函数时替换成员功能是虚拟和非虚拟的。有人帮我理解吗?

我想更多地了解此链接说明:http://www.learncpp.com/cpp-tutorial/8-8-thenden-hidded-hidded-thide-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;
}

谢谢

您的代码显示未定义的行为,这意味着编译器可以执行自己喜欢的任何事情,包括您的(错误)期望做。