赢 7 赛格文 gcc 4.8.3 -std=gnu++11
我已经在 stackoverflow 和 cplusplus 上对此进行了研究,并认为我已经正确地将函数作为参数传递,甚至是“优雅地”传递,但很明显我误解了一些东西。任何人都可以解释如何正确地将函数作为参数传递,以及为什么我所拥有的不起作用?
为原型(prototype)给出了一个警告,为调用给出了一个错误。在评论中将 genX 更改为 genY,但 genX 和 genY 都有相同的警告/错误。
class MyClass {
typedef double (*func_t)(double sum);
void driver();
double genX(func_t fnc) { };
double genY(double (*funct)(double sum)) { };
// note: no known conversion for argument 1 from
// '<unresolved overloaded function type>' to
// MyClass::func_t {aka double (*)(double)}
double myThingie(double sum) { };
};
void MyClass::driver() {
genX(myThingie);
genY(myThingie);
// no matching function for call to 'MyClass::genX(<unresolved overloaded function type>)'
}
最佳答案
"Can anyone explain how to pass a function as an argument correctly, and why what I have won't work?"
你需要
typedef double (MyClass::*func_t)(double sum);
// ^^^^^^^^
为成员类函数声明函数指针。
然后获取他们的地址
genX(&MyClass::myThingie);
genY(&MyClass::myThingie);
关于c++ - 如何将函数作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27820994/