Gab*_*les 4 c++ pointers function-pointers function
好吧,我认为标题足够描述(但令人困惑,抱歉).
我正在读这个库:Timer1.
在头文件中有一个指向函数的公共成员指针,如下所示:
class TimerOne
{
public:
void (*isrCallback)();
};
Run Code Online (Sandbox Code Playgroud)
存在TimerOne类的实例化对象,称为"Timer1".
Timer1调用该函数如下:
Timer1.isrCallback();
Run Code Online (Sandbox Code Playgroud)
这怎么回事?我熟悉通过使用dereference运算符通过函数指针调用函数.
例如:
(*myFunc)();
Run Code Online (Sandbox Code Playgroud)
所以我希望通过对象的上述调用更像是:
(*Timer1.isrCallback)();
Run Code Online (Sandbox Code Playgroud)
那么,通过函数指针调用函数的可接受选项是什么,作为独立的函数指针和对象的成员?
您可以使用函数指针执行的操作。
\n\n1:第一个是通过显式取消引用调用函数:
\n\nint myfunc(int n)\n{\n}\n\nint (*myfptr)(int) = myfunc; \n\n(*myfptr)(nValue); // call function myfunc(nValue) through myfptr.\nRun Code Online (Sandbox Code Playgroud)\n\n2:第二种方式是通过隐式取消引用:
\n\nint myfunc(int n)\n{\n}\n\nint (*myfptr)(int) = myfunc;\n\nmyfptr(nValue); // call function myfunc(nValue) through myfptr.\nRun Code Online (Sandbox Code Playgroud)\n\n正如您所看到的,隐式取消引用方法看起来就像一个普通的函数调用——这就是您\xe2\x80\x99d所期望的,因为函数可以简单地隐式转换为函数指针!
\n\n在你的代码中:
\n\nvoid foo()\n{\n cout << "hi" << endl;\n}\n\nclass TimerOne\n{\npublic:\n\n void(*isrCallback)();\n};\n\n\nint main()\n{\n\n TimerOne Timer1;\n Timer1.isrCallback = &foo; //Assigning the address\n //Timer1.isrCallback = foo; //We could use this statement as well, it simply proves function are simply implicitly convertible to function pointers. Just like arrays decay to pointer.\n Timer1.isrCallback(); //Implicit dereference\n (*Timer1.isrCallback)(); //Explicit dereference\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n
您不必取消引用函数指针来调用它.根据标准([expr.call]/1),
后缀表达式应具有函数类型或指向函数类型的指针.
所以(*myFunc)()是有效的,也是如此myFunc().事实上,(**myFunc)()也是有效的,你可以根据需要多次取消引用(你能弄明白为什么吗?)