相关疑难解决方法(0)

为什么使用函数名作为函数指针等效于将address-of运算符应用于函数名?

有趣的是,将函数名称用作函数指针等同于将address-of运算符应用于函数名称!

这是一个例子.

typedef bool (*FunType)(int);
bool f(int);
int main() {
  FunType a = f;
  FunType b = &a; // Sure, here's an error.
  FunType c = &f; // This is not an error, though. 
                  // It's equivalent to the statement without "&".
                  // So we have c equals a.
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

使用这个名称是我们在数组中已经知道的.但是你不能写出类似的东西

int a[2];
int * b = &a; // Error!
Run Code Online (Sandbox Code Playgroud)

这似乎与该语言的其他部分不一致.这个设计的基本原理是什么?

这个问题解释了这种行为的语义及其工作原理.但是我对这种语言设计的原因很感兴趣.

更有趣的是,当用作参数时,函数类型可以隐式转换为指向自身的指针,但在用作返回类型时不会转换为指向自身的指针!

例:

typedef bool FunctionType(int);
void g(FunctionType); // Implicitly converted to void g(FunctionType …
Run Code Online (Sandbox Code Playgroud)

c++ syntax function-pointers

16
推荐指数
2
解决办法
6040
查看次数

为什么可以使用函数作为 if 语句条件而不调用它?

我想知道为什么这段代码的两个版本都没有错误:

#include <iostream>

bool check_number(int n) {
    return n < 5;
}

int main() {
    int number = 6;

    // (1) prints "Hello World"
    if (check_number)
    // (2) prints "not hello world"
    if (check_number(number))
    {
        std::cout << "Hello world!";
    }
    else
    {
        std::cout << "not hello world";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Hello world!尽管我没有将变量传递到if 语句中的number函数中,但条件 (1) 仍会打印。check_number

在情况(2)中,我得到了not hello world预期的结果。

c++ function-pointers implicit-conversion

3
推荐指数
3
解决办法
147
查看次数