好吧,我认为标题已经足够描述了(但令人困惑,抱歉)。
我正在阅读这个库: Timer1 。
在头文件中有一个指向函数的公共(public)成员指针,如下所示:
class TimerOne
{
public:
void (*isrCallback)();
};
存在 TimerOne 类的实例化对象,称为“Timer1”。
Timer1 调用函数如下:
Timer1.isrCallback();
这是如何正确的?我熟悉使用取消引用运算符通过函数指针调用函数。
前任:
(*myFunc)();
所以我希望通过对象进行的上述调用更像是:
(*Timer1.isrCallback)();
那么,作为独立函数指针和对象成员,通过函数指针调用函数的可接受选项是什么?
最佳答案
你可以用函数指针做的事情。
1: 第一个是通过显式解引用调用函数:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
(*myfptr)(nValue); // call function myfunc(nValue) through myfptr.
2: 第二种方式是通过隐式解引用:
int myfunc(int n)
{
}
int (*myfptr)(int) = myfunc;
myfptr(nValue); // call function myfunc(nValue) through myfptr.
正如你所看到的,隐式解引用方法看起来就像一个普通的函数调用——这正是你所期望的,因为函数可以简单地隐式转换为函数指针!!
在您的代码中:
void foo()
{
cout << "hi" << endl;
}
class TimerOne
{
public:
void(*isrCallback)();
};
int main()
{
TimerOne Timer1;
Timer1.isrCallback = &foo; //Assigning the address
//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.
Timer1.isrCallback(); //Implicit dereference
(*Timer1.isrCallback)(); //Explicit dereference
return 0;
}
关于通过具有指向函数的公共(public)成员指针的对象调用 C++ 函数,而不使用解引用运算符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31869026/