打印虚拟成员函数的地址 [英] print address of virtual member function
本文介绍了打印虚拟成员函数的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印虚拟成员函数的地址。
如果我只想打印函数的地址,我可以写:
I am trying to print the address of a virtual member function. If I only wants to print the address of the function I can write:
print("address: %p", &A::func);
但我想这样做:
A *b = new B();
printf("address: %p", &b->func);
printf("address: %p", &b->A::func);
然而这不编译,是可能做这样的事情甚至做
vb中的地址是否在运行时完成?
however this does not compile, is it possible to do something like this even do looking up the address in the vtable is done in runtime?
推荐答案
此代码是否打印正确的地址?它将在vtable中打印函数的地址,但是是正确的:)
Will this code print the right address? It will print the address of the function in the vtable, but is it correct:)?
struct A
{
virtual void func() { cout << "A::func" << endl; }
};
struct B : public A
{
void func() { cout << "B::func" << endl; }
};
typedef void (*functionPtr)();
int main()
{
A *b = new B();
int *vptr = *(int**)&b;
int *vtable = (int *)*vptr;
functionPtr fp = (functionPtr)vtable[0];
printf("address A::func = %p\n", fp);
return 0;
}
这篇关于打印虚拟成员函数的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文