【发布时间】:2014-12-22 23:44:50
【问题描述】:
我试图了解函数指针是如何工作的。这是代表设置:
bool f1(int x){
if(condition){return true;}
else return false;
}
bool f2(int x, bool (*func)(int)){
if (func(x)){return true;}
else return false;
}
void f3(int x, bool (*func)(int, bool)){
if (func(x, f1)) {return "Whatever";}
else return "Nevermind";
int main(){
f3(x, f2);
}
这给了我:
在函数 'void f3()' 中:
"警告:bool 'f1(int)' 的地址将始终评估为 'true' [-Waddress]
在函数“int main()”中:
错误:从 'bool ()(int,bool ()(int))' 到 'bool (*)(int, bool)' 的无效转换
我搞砸了多少?
【问题讨论】:
-
您正在传递函数
f1的地址,您可能想调用它。 -
你应该养成
return condition;的习惯,而不是if(condition) return true; else return false;。它更简单、更短,而且做同样的事情。
标签: c++ function-pointers