引用:[33.11] Can I convert a pointer-to-function to a void*?
#include "stdafx.h"
#include <iostream>
int f(char x, int y) { return x; }
int g(char x, int y) { return y; }
typedef int(*FunctPtr)(char,int);
int callit(FunctPtr p, char x, int y) // original
{
return p(x, y);
}
int callitB(FunctPtr p, char x, int y) // updated
{
return (*p)(x, y);
}
int _tmain(int argc, _TCHAR* argv[])
{
FunctPtr p = g; // original
std::cout << p('c', 'a') << std::endl;
FunctPtr pB = &g; // updated
std::cout << (*pB)('c', 'a') << std::endl;
return 0;
}
问题> 推荐的方法是原始方法还是更新方法? 我已经使用 VS2010 测试了这两种方法,并且每种方法都打印了正确的结果。
谢谢
尽管我确实在原帖中看到了以下用法:
void baz()
{
FredMemFn p = &Fred::f; ← declare a member-function pointer
...
}
最佳答案
取消引用一个函数指针会产生另一个函数指针。所以,只需 f()
,否则您只是在混淆您的代码。
指向成员的指针完全不同。它们需要使用 .*
或 ->*
运算符。这也是您应该使用 std::function
(或 boost::function
)而不是指向函数/成员的原始指针的原因。
关于c++ - 当 p 是函数指针时,我们应该使用 p(..) 还是 (*p)(..)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231273/