【问题标题】:Why will "the adress of bool will always evaluate as true" here?为什么在这里“布尔地址将始终评估为真”?
【发布时间】: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


【解决方案1】:
void f3(int x, bool (*func)(int, bool)){
                                 ^^^^

f3 的第二个参数是指向第二个参数为 bool 的函数的指针。

f2 是您要传递给f3 并从f3 调用的函数类型,但f2 的第二个参数类型为bool (*)(int)

所以f3 应该相应地声明:

void f3(int x, bool (*func)(int, bool (*)(int)))

注意:这可以通过适当地使用typedef 来提高可读性:

typedef bool f1_t(int);
typedef bool f2_t(int, f1_t*);

bool f1(int x) { ... }
bool f2(int x, f1_t* func) { ... }
void f3(int x, f2_t* func) { ... }

【讨论】:

    【解决方案2】:

    如果您直接从函数的地址生成函数指针,它将始终为非空指针,并且只有空指针的计算结果为false

    func 的第二个参数必须是 bool,但您传递给它的是函数的名称。该函数会自动转换为指向该函数的指针,然后使用上述规则将其自动转换为bool

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2014-05-19
      • 2013-11-16
      • 1970-01-01
      • 2022-01-11
      相关资源
      最近更新 更多