[英]using functions of non-static class functions in C++
I have a class containing several functions, and I would like to be able to use functions of these functions.我有一个包含多个功能的 class,我希望能够使用这些功能的功能。 When I try to do something like the code below, I keep getting the compiler error message "invalid use of non-static member function".
当我尝试执行类似以下代码的操作时,我不断收到编译器错误消息“无效使用非静态成员函数”。
class MyClass{
protected:
void f(int a, int b);
void g(int num);
void do_something_with_function(int count, void func(int, int));
...
...
};
void MyClass::do_something_with_function(int count, void func(int, int)){
for(int i=0; i<count; i++){
for(int x=0; x<5; x++){
for(int y=0; y<3; y++){
func(x,y);
}
}
}
}
void MyClass::f(int a, int b){
std::cout<<"a="<<a<<", b="<<b<<std::endl;
}
void MyClass::g(int num){
do_something_with_function(num, f);
}
Is there a way to get this to work without making f
(and all of the functions on which f
depends) static?有没有办法在不使
f
(以及f
依赖的所有函数)static 的情况下使其工作?
Yes, you just need to accept a pointer to member function, not a regular function.是的,您只需要接受指向成员 function 的指针,而不是常规的 function。
Change the definition to:将定义更改为:
void MyClass::do_something_with_function(int count,
void (MyClass::*func)(int, int)) {
// ...
func(1, 2); // and use func
}
(and the declaration must be changed as well, of course), and call the function like this: (当然,声明也必须更改),并像这样调用 function:
do_something_with_function(num, &MyClass::f);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.