gpt4 book ai didi

c++ - 在C++中使用非静态类函数的函数

转载 作者:行者123 更新时间:2023-12-02 10:56:29 25 4
gpt4 key购买 nike

我有一个包含几个函数的类,并且我希望能够使用这些函数中的函数。当我尝试执行类似以下代码的操作时,我不断收到编译器错误消息“无效使用非静态成员函数”。

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);
}

有没有一种方法可以在不使 f(以及 f所依赖的所有函数)静态的情况下工作呢?

最佳答案

是的,您只需要接受指向成员函数的指针,而不是常规函数。

将定义更改为:

void MyClass::do_something_with_function(int count, 
void (MyClass::*func)(int, int)) {
// ...
func(1, 2); // and use func
}

(当然,声明也必须更改),然后像下面这样调用函数:
do_something_with_function(num, &MyClass::f);

这是 demo

关于c++ - 在C++中使用非静态类函数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62272549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com