[英]Code replaced by compiler for Function pointers of member functions
在以下示例中,我很难理解关于成员函数的函数指针调用。
(f.*(FPTR) bp)(0); // This call b()
(b.*(BPTR) fp)(0); // This call f()
我想知道被替换的代码(因为我知道像obj.Fun()这样的函数调用在这两个成员函数是虚拟的和非虚拟的时,被这两个函数调用的编译器替换为Fun(&obj) 。有人帮助我了解,请吗?
我想了解更多类似此链接的说明: 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;
}
谢谢
您的代码显示未定义的行为 ,这意味着编译器可以执行其喜欢的任何操作, 包括您 (错误地) 期望它执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.