C++ C++;指向函数的指针导致seg故障
我有点麻烦。我似乎不明白为什么我的主函数在没有seg错误的情况下不能调用intFunction指向的函数 此外,这是我用于测试目的的代码。对于C++,我还是相当新的。 谢谢你的帮助C++ C++;指向函数的指针导致seg故障,c++,function,pointers,segmentation-fault,C++,Function,Pointers,Segmentation Fault,我有点麻烦。我似乎不明白为什么我的主函数在没有seg错误的情况下不能调用intFunction指向的函数 此外,这是我用于测试目的的代码。对于C++,我还是相当新的。 谢谢你的帮助 #include <iostream> int tester(int* input){ std::cout << "\n\n" << *input << "\n\n"; } int (*intFunction)(int*); template<typ
#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;
}
#包括
内部测试仪(内部*输入){
std::cout当将函数指针作为参数传递时,它们与其他变量没有任何区别,因为您传递的是值的副本(即,它当时拥有的任何函数地址)
如果要在另一个函数中指定变量,则必须通过引用或作为指向原始变量的指针进行传递
通过引用:
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);
您从未给过intFunction
一个值(0/NULL/nullptr除外,因为它是全局的)。请尝试int(*intFunction)(int*)=&tester;
您已通过值将intFunction
传递给passFunction
——这与本例中的任何其他指针一样。请尝试通过引用传递,或将指针传递给FT,然后分配其解引用。