函数指针说明
function pointer explanation
我正在学习C++,只是玩函数指针。
我有这个非常简单的程序,但是调用时没有获得任何输出。你介意解释一下为什么吗?我想这是因为在printTheNumbers
内部,我从来没有调用函数本身,我只是引用它?
void sayHello()
{
cout << "hello there, I was accessed through another functionn";
}
void accessFunctionThroughPointer(int a, int b, void(*function)())
{
}
int main(int argc, const char * argv[])
{
printTheNumbers(2, 3, sayHello);
return 0;
}
你的函数没有做任何事情:
void printTheNumbers(int a, int b, void (*function)()){
// there is no body here
}
您需要实际调用传入的函数指针:
void printTheNumbers(int a, int b, void (*function)()){
function();
}
你传入sayHello函数来打印TheNumbers,但你从不调用传递的函数。
您需要手动调用该函数。证明:
代码片段
更考虑使用std::function
。例:
#include <functional>
void printTheNumbers(int a, int b, std::function<void()> function){
function();
}
在大多数情况下,std::函数就足够了,而且更具可读性。
相关文章:
- 当使用通配符和null指针调用函数时,对输出的说明
- 关于C++中具有多重继承"this"指针的说明
- 指针数组说明
- 有关通过引用传递指针的说明
- 说明通过指针访问非静态类成员函数
- 了解 ARM 程序集说明和 C/C++ 指针
- 该指针操纵功能的说明
- 请求对数组中指针行为的说明
- 模板化函数指针说明
- C /参考操作员和指针中的插座连接()函数说明
- 函数指针说明
- C++指针分配说明
- C++03 12.4/12对通过指针显式调用基类析构函数有何说明
- 函数指针的说明
- 有关 c++ 中指针的说明
- 指针分配说明
- 关于指向非静态类成员的指针的说明
- 对指向函数转换的指针的说明
- 无法'this'指针从'const Line'转换为'Line &'说明?
- 关于智能指针运算符*和运算符>重载的说明