指向类成员的指针
在我的班级中,如果我想指向类的成员,
struct S
{
static int get();
int do_something();
int x;
};
我会这样做,
int (*p)() = S::get;
不幸的是,这不适用于非静态成员
int (*p)() = S::do_something; // error
,因为静态成员函数是一个普通函数,并且从我在下面引用的引用中可以看出,非静态成员函数也是一个普通函数,为什么它不起作用呢?这是什么意思?
(9.2/10) [注意:非静态成员函数的类型是普通的 函数类型,非静态数据成员的类型是普通的 对象类型。没有特殊的成员函数类型或数据成员 类型。 ]
In my class, If I want to point to a member of class,
struct S
{
static int get();
int do_something();
int x;
};
I do,
int (*p)() = S::get;
Unfortunately this doesn't for non-static member
int (*p)() = S::do_something; // error
Since, a static member function is an ordinary function, and from the quote I came around below states that a non-static member function is also a ordinary function so why wouldn't it work? what does it mean?
(9.2/10) [Note: the type of a nonstatic member function is an ordinary
function type, and the type of a nonstatic data member is an ordinary
object type. There are no special member function types or data member
types. ]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
非静态成员函数不是普通函数。您无法形成指向它们的自由指针。
引用非静态成员函数的唯一允许的方法是通过实例指针/引用和指向成员函数的指针的对:
与成员对象不同(您可以很好地形成一个自由指针,例如
&theobject.x
),成员函数更复杂,因为您需要考虑虚函数:如果S
> 是一个多态基类,p
是一个指向基点的指针并且 do_something() 是虚拟的,那么上面的示例应该执行正确类型的调度。简单的自由函数指针无法做到这一点。(此外,标准没有指定成员函数的每个底层实现是如何实现的,因此这个细节永远不会暴露给用户。通常它会类似于 int S_mangled_name_do_something(S *); code>,但未指定。)
以下是我关于该主题的一些相关答案:#1,#2 >。
Non-static member functions are not ordinary functions. You cannot form free pointers to them.
The only permissible way to refer to a non-static member function is through a pair of an instance pointer/reference and a pointer-to-member-function:
Unlike member objects (to which you can very well form a free pointer, e.g.
&theobject.x
), member functions are more complicated, because you need to account for virtual functions: IfS
is a polymorphic base class andp
is a pointer-to-base anddo_something()
is virtual, then the above example should perform the correct type of dispatch. A simple free function pointer cannot do this.(Moreover, the standard does not specify how each underlying implementation of member functions is implemented, so this detail is never exposed to the user. Typically it'll be something like
int S_mangled_name_do_something(S *);
, but that's not specified.)Here are some related answers of mine on the subject: #1, #2.
函数的类型是普通的,而不是函数指针的类型。指向非静态成员函数的指针必须这样声明:
The type of the function is ordinary, not the type of the function-pointer. A pointer to a non-static member-function has to be declared like this:
非静态成员函数除了有一个不可见的参数this之外,就是一个普通的函数。
a non-static member function is an ordinary function except that there is an invisible parameter this.