指向虚拟成员函数的指针。它是如何工作的? [英] Pointers to virtual member functions. How does it work?

查看:129
本文介绍了指向虚拟成员函数的指针。它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下C ++代码:

Consider the following C++ code:

class A
{
public:
      virtual void f()=0;
};


int main()
{
     void (A::*f)()=&A::f;
}

如果我不得不猜测,我会说& A :: f在这个上下文中意味着A的实现f()的地址,因为在指向正常成员函数和虚拟成员函数的指针之间没有显式的分隔。并且由于A不实现f(),这将是一个编译错误。但是不是。

If I'd have to guess, I'd say that &A::f in this context would mean "the address of A's implementation of f()", since there is no explicit seperation between pointers to regular member functions and virtual member functions. And since A doesn't implement f(), that would be a compile error. However, it isn't.

不仅如此。以下代码:

void (A::*f)()=&A::f;
A *a=new B;            // B is a subclass of A, which implements f()
(a->*f)();

实际上会调用B :: f。

will actually call B::f.

推荐答案

这里有太多关于成员函数指针的信息。有一些关于虚拟函数的良好的编译器,虽然IIRC当我阅读的文章我正在skimming那部分,因为这篇文章实际上是关于在C ++中实现委托。

Here is way too much information about member function pointers. There's some stuff about virtual functions under "The Well-Behaved Compilers", although IIRC when I read the article I was skimming that part, since the article is actually about implementing delegates in C++.

http://www.codeproject.com/KB /cpp/FastDelegate.aspx

简单的答案是它依赖于编译器,但是一种可能性是成员函数指针被实现为struct包含指向thunk函数的指针,该函数进行虚拟调用。

The short answer is that it depends on the compiler, but one possibility is that the member function pointer is implemented as a struct containing a pointer to a "thunk" function which makes the virtual call.

这篇关于指向虚拟成员函数的指针。它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆