成员函数的函数指针由编译器替换的代码
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)当这些成员函数是虚函数和非虚函数时调用两个函数。
任何人都可以帮助我理解吗?
我想了解更多类似这样link解释: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;
}
谢谢
您的代码显示 undefined behaviour,这意味着编译器可以做任何它喜欢的事情,包括您(错误地)期望[=15] =] 它来做。
在下面的例子中,我很难理解关于成员函数的函数指针调用。
(f.*(FPTR) bp)(0); // This call b()
(b.*(BPTR) fp)(0); // This call f()
我想知道替换的代码 (据我所知,像 obj.Fun() 这样的函数调用被编译器替换为 Fun(&obj)当这些成员函数是虚函数和非虚函数时调用两个函数。 任何人都可以帮助我理解吗?
我想了解更多类似这样link解释: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;
}
谢谢
您的代码显示 undefined behaviour,这意味着编译器可以做任何它喜欢的事情,包括您(错误地)期望[=15] =] 它来做。