[英]Is it possible to create a pointer to a non-static member-function in C++?
I was wondering if it's possible to create and use a pointer to a non-static member-function. 我想知道是否可以创建和使用指向非静态成员函数的指针。 When I compile my code without the pointer to the member-function being static, it gives a compilation error.
当我在没有成员函数指针为静态的情况下编译代码时,会出现编译错误。
Thanks... 谢谢...
In short: Yes, it's possible, and no, it doesn't do what you think. 简而言之:是的,有可能,没有,它没有按照您的想法做。
The crucial fact is that non-static member functions are not functions (just like a Douglas-fir is not a fir). 关键事实是非静态成员函数不是函数(就像花旗松不是冷杉)。 They are member functions, and that's something different.
它们是成员函数,而有所不同。 They can only be invoked on a given object instance.
它们只能在给定的对象实例上调用。
Thus in order to call the member function X::foo()
of a given instance X a;
因此,为了调用给定实例
X a;
的成员函数X::foo()
X a;
, ie to perform the call a.foo()
, you need both the information that you want to use X::foo()
, and that you want to invoke it on the instance a
. ,即执行调用
a.foo()
,既需要使用X::foo()
,又需要在实例a
上调用它a
。 The former is provided by a pointer-to-member-function , which is not a pointer , and the latter is provided by an instance pointer or reference: 前者由指针到成员函数提供 ,后者不是指针 ,后者由实例指针或引用提供:
struct X { int foo(bool, char); }; // class definition
X a; // an instance
X * p = &a; // just for demonstration
int (X::*)(bool, char) ptmf = &X::foo; // pointer-to-member-function
Now to invoke: 现在调用:
(a.*ptmf)(false, 'a');
(p->*ptmp)(true, 'z');
In a nutshell: foo
alone does not let you call anything. 简而言之:
foo
本身不能让您调用任何东西。 The callable entity is the pair (&X::foo, a)
, which lets you call a.foo()
. 可调用实体是对
(&X::foo, a)
,可让您调用a.foo()
。
Yes, it is possible to create pointer to member functions in C++. 是的,可以在C ++中创建指向成员函数的指针。 See this FAQ: pointers-to-members
查看此常见问题解答: 指向成员的指针
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.