我遇到了一些麻烦。我似乎无法弄清楚为什么我的 main 函数不能在没有段错误的情况下调用 intFunction 指向的函数。
此外,这是我用于测试目的的代码。我对 C++ 还是很陌生。
感谢您的帮助。
#include <iostream>
int tester(int* input){
std::cout << "\n\n" << *input << "\n\n";
}
int (*intFunction)(int*);
template<typename FT>
int passFunction(int type, FT function){
if(type == 1){
function = tester;
//Direct call...
tester(&type);
int type2 = 3;
//Works from here...
function(&type2);
}
return 0;
}
int main(int argc, char* argv[]){
passFunction(1,intFunction);
int alert = 3;
//But not from here...
intFunction(&alert);
return 0;
}
最佳答案
当将函数指针作为参数传递时,它们与其他变量没有任何不同,因为您传递的是值的拷贝(即它当时具有的函数地址)。
如果你想在另一个函数中分配一个变量,你必须通过引用或作为指向原始变量的指针传递它。
引用:
int passFunction(int type, FT& function)
或者作为指针
int passFunction(int type, FT* ppfunction)
{
if(type == 1)
{
*ppfunction = tester;
//Direct call...
tester(&type);
int type2 = 3;
//Works from here...
(*ppfunction)(&type2);
}
return 0;
}
// which then requires you pass the address of your variable when
// calling `passFunction`
passFunction(1, &intFunction);
关于指向函数的 C++ 指针导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25270471/