关于指向非静态类成员的指针的澄清
当我需要指向类成员的指针时,我会执行以下操作
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果它是静态函数,它的工作方式就像常规非成员函数指针:函数名称本身可以隐式转换为函数指针。
如果它是一个非静态成员函数,它就不再与非成员函数是一回事了:
this
参数;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:
this
parameter;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.
您是对的,在指向成员函数语法的指针的情况下,理想情况下可以省略
&
。我认为,由于历史惯例,&
语法的存在可能。这是不正确的。唯一的区别是它们是指向成员函数的指针。由于
class
非静态成员包含一个隐式this
指针作为其参数,因此它们具有特殊的签名。此外,它们不能与具有相同签名的普通函数指针相互转换。在您的代码示例中,理论上
p
指向: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.That's not correct. The only difference is that they are pointer to member function. Since,
class
non-static member contain an implicitthis
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: