简体   繁体   English

是否可以在C ++中创建指向非静态成员函数的指针?

[英]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.

相关问题 将函数指针传递给非静态成员函数 - pass function-pointer to non-static member-function 将成员函数作为函数变量传递时,无效使用非静态成员函数C ++ - invalid use of non-static member function C++ while passing member-function as a function variable C ++将指针传递给非静态成员函数 - C++ Passing pointer to non-static member function 使用模板的非静态成员函数的C ++指针 - C++ Pointer to Non-static Member Function Using Templates C++:如何返回指向非静态成员 function 的指针? - C++: How to return a pointer to a non-static member function? C ++成员函数指针 - C++ member-function pointer 指向模板类的非静态成员函数的C ++函数指针(类成员) - C++ function pointer (class member) to non-static member function of a template class C ++函数指针(类成员)到非静态成员函数 - C++ function pointer (class member) to non-static member function 如何将C ++函数指针(非静态成员函数)传递给预定义的C函数? - How to pass in a C++ function pointer (of non-static member function) to a pre-defined C Function? C ++函数接受函数指针和非静态成员函数作为参数 - C++ function accepting function pointer and non-static member function as parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM