指向成员函数的C ++函数指针

编程入门 行业动态 更新时间:2024-10-20 08:53:25
本文介绍了指向成员函数的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 ++函数指针

本文发布于:2023-07-29 00:45:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235669.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   指针   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!