【问题标题】:Defining a function inside the input of another function in C在 C 中另一个函数的输入中定义一个函数
【发布时间】:2015-06-06 14:12:17
【问题描述】:

我有一个函数,它有一个函数指针输入。我可以轻松地将函数名称作为输入。但我想知道是否可以将函数定义为输入。例如我有这样的功能;

void exampleFunction ( void (*functionPointer)( void ) ) {
  codes
  ...
}

我可以在括号内给出这样的输入吗?例如;

exampleFunction( void helloFunction ( void ) {
  printf("Hello");
} );

它会出现这样的编译错误,但还有其他方法吗?

【问题讨论】:

  • “其他”方式暗示 this 是一种。
  • 天啊,好问题。我看到这些东西的次数越多,我就越不了解 C 中的编码,而不是 C++。如果您不喜欢,请不要使用异常、虚函数或其他任何东西。

标签: c++ c function input function-pointers


【解决方案1】:

这在 C 中是不可能的。

在 C++ 中,您可以使用 lambda 表达式:

exampleFunction([](){ std::cout << "Hello"; });

【讨论】:

  • 哈哈哈哈!非常非常感谢你!!! :D 它确实有效,因为我使用的 Arduino IDE 也支持 C++。我用 C++ lambda-expression 写了一些 C 代码,它成功了!我知道这不是一个好的解决方案,但我现在很高兴:D 再次感谢...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 2012-01-15
  • 2019-03-01
  • 1970-01-01
  • 2021-06-27
  • 2018-07-04
相关资源
最近更新 更多