c++ - 指向函数赋值的指针

标签 c++ function-pointers

为什么不带'&'的赋值在下面的代码中编译?我用 GCC 3.4.6 编译了代码。不带 & 赋值是否正确,或者这是 GCC 的“特性”?

void func() {
}

int main() {
  typedef void (*F)();

  F f;
  f = &func; // the way of assigning pointer to function.
  f = func;  // this is also working.

  (*f)();

  return 0;
}

最佳答案

这完全没问题。这两种说法是完全等价的。函数左值通过标准转换转换为指向函数的指针。 §4.3/1:

An lvalue of function type T can be converted to an rvalue of type “pointer to T.” The result is a pointer to the function.

关于c++ - 指向函数赋值的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245829/

相关文章:

c++ - 我的 Qt 代码不能用 "cannot call member function without object"编译

c++ - 模板专用类之间的构造函数重载

c - 从文件读取字符串并将字符串存储到 C 中的多维字符串数组中

c - 如何使用alloca分配C函数指针?

c++ - 可以取消引用函数指针吗

ZeroMemory 的 C# 等效代码

c++ - 运行函数 GetVolumeInformation() 时我得到非常随机的结果

c++ - constexpr 是编译器的 "hint"(如内联)还是 "a binding request"?

c++ - 从调用堆栈中获取函数指针

r - 使用函数作为参数时为 "could not find function"