如何在 C++ 中指向一个函数

How to Point to a Function in C++

我想知道如何创建一个指向函数地址指针

假设我们有以下函数:

int doublex(int a)
{
    return a*2;
}

我已经知道&用于获取地址。我怎么能指向这个函数?

就这样:

auto function_pointer = &doublex;

什么是 auto 类型?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime. Source here

这将对您有所帮助:C++ auto keyword. Why is it magic?

您可以这样做并存储对兼容函数的引用或将您的函数作为另一个函数的参数传递。

typedef int (*my_function_type)(int a);
int double_number(int a)
{
    return a*2;
}
my_function_type my_function_pointer = double_number;
int transform_number(int target, my_function_type transform_function) {
    return transform_function(target);
}

希望对你有帮助

如前所述,您可以使用 & 运算符获取地址。那么最简单的方法就是给它分配一个 auto 变量来存储它,现在你可以像使用函数本身一样使用你的变量。

int doubleNumber(int x)
{
    return x*2;
}

int main()
{
  auto func = &doubleNumber;
  std::cout << func(3);
}

查看实例 here