指向成员函数的C ++函数指针-它接收哪个地址? [英] C++ function pointer to a member function - which address does it receive?

查看:96
本文介绍了指向成员函数的C ++函数指针-它接收哪个地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个课程:

class Shape
{
public:
    int value;

    Shape(int v) : value(v) {};

    void draw()
    {
        cout << "Drawn the element with id: " << value << endl;
    }
};

和以下代码(有效)

    Shape *myShapeObject = new Shape(22);

    void (Shape::*drawpntr)();
    drawpntr = &Shape::draw;

    (myShapeObject ->*drawpntr)();

我有一个drawpntr函数指针,指向类Shape的一个返回空值的0参数函数成员.

I have a drawpntr function pointer to a void-returning 0-arguments function member of the class Shape.

我想问的第一件事:

drawpntr = &Shape::draw;

该函数是成员函数,并且这里没有对象..drawpntr接收什么地址?该类甚至不应该存在

the function is a member function and there's no object here.. what address does drawpntr receive? The class shouldn't even exist

我同意这句话

(myShapeObject->*drawpntr)();

因为我知道我不能取消引用成员函数的函数指针(无对象->无函数),但是drawpntr中实际上存储了什么地址?

because I understand I cannot de-reference a function pointer to a member function (no object -> no function), but what address is actually stored in drawpntr?? There's no object when the

drawpntr = &Shape::draw;

行被调用..并且该类也不应该作为实体存在

line is invoked.. and the class shouldn't exist either as an entity

推荐答案

所有成员函数共享相同的代码,因此它们在内存的代码段中具有相同的地址.成员函数仅在不同的实例上运行,因为它们隐式地传递了this指针的不同值.它们不以任何方式与它们在其上运行的任何实例相关联.如果功能不是虚拟的,则可以静态确定drawpntr的实际值,也可以动态确定(通过 vtable )(如果该函数是虚拟的.

All member functions share the same code, so they have the same address in the code segment of memory. Member functions operate on different instances only because they are implicitly passed different values of this pointer. They are not tied in any way to any of the instances on which they operate. The actual value of drawpntr could be determined statically if the function is non-virtual, or dynamically (through the vtable) if the function is virtual.

这篇关于指向成员函数的C ++函数指针-它接收哪个地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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