关于指向非静态类成员的指针的澄清

发布于 2024-12-22 01:19:23 字数 221 浏览 2 评论 0原文

当我需要指向类成员的指针时,我会执行以下操作

struct MyStruct
{
    int foo();
};

int (MyStruct::*p)() = &MyStruct::foo;

我的问题是为什么我需要使用 &运算符获取地址,如果它是静态函数,则可以忽略该地址。另外,我听说指向成员的指针并不是真正的指针,有人可以澄清一下吗?

When I need a pointer to member of class, I do as following

struct MyStruct
{
    int foo();
};

int (MyStruct::*p)() = &MyStruct::foo;

My question is why do I need to use & operator to take the address which may be ignored if it were a static function. Also, I've heard pointer to members aren't really a pointer, Can someone clarify that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

那伤。 2024-12-29 01:19:23

如果它是静态函数,它的工作方式就像常规非成员函数指针:函数名称本身可以隐式转换为函数指针。

如果它是一个非静态成员函数,它就不再与非成员函数是一回事了:

  1. 它有一个隐藏的 this 参数;
  2. 在多重继承场景中,将指针转换为基类之一可能会产生指向不同地址的指针。这意味着如果成员函数是继承的,则在调用之前可能需要调整this指针。这已经使得不可能使用指针来存储指向成员函数的指针。

雷蒙德·陈 就此写了一篇有趣的文章,其中包含更多详细信息和示例。

If it's a static function, it works just as a regular non-member function pointer: the function name itself can be implicitly converted to a function pointer.

If it's a non-static member function, it's no longer the same thing as a non-member function:

  1. It has a hidden this parameter;
  2. In a multiple inheritance scenario, converting a pointer to one of the base classes may produce a pointer to a different address. This means that if the member function is inherited, the this pointer may need to be adjusted before the call. This already makes it impossible to use a pointer to store a pointer-to-member-function.

Raymond Chen wrote an interesting article about this with more details and examples.

哆啦不做梦 2024-12-29 01:19:23

为什么我需要使用&运算符获取的地址可能是
如果是静态函数则忽略

您是对的,在指向成员函数语法的指针的情况下,理想情况下可以省略 & 。我认为,由于历史惯例, & 语法的存在可能

我听说指向成员的指针并不是真正的指针,有人可以吗
澄清一下吗?

这是不正确的。唯一的区别是它们是指向成员函数的指针。由于class非静态成员包含一个隐式this指针作为其参数,因此它们具有特殊的签名。此外,它们不能与具有相同签名的普通函数指针相互转换。

在您的代码示例中,理论上 p 指向:

int MyStruct::foo (MyStruct* const);

why do I need to use & operator to take the address which may be
ignored if it were a static function

You are right, in the case of pointer to member function syntax ideally & can be omitted. I think, & syntax is there may be due to historical convention.

I've heard pointer to members aren't really a pointer, Can someone
clarify that?

That's not correct. The only difference is that they are pointer to member function. Since, class non-static member contain an implicit this pointer as their argument, they have a special signature. Also, they are not inter-convertible with normal function pointer with same signature.

In your code example, theoritically p is pointing to:

int MyStruct::foo (MyStruct* const);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文