最近复习C++,突然看到函数指针,由于自己上学期C++学习的比较水,所以在这里专门总结一下。 与普通的指针相似,指向函数的指针包含内存中该函数的地址。对比数组,数组名实际是数组的第一个元素在内存中的地址。类似的,函数名实际上是这个函数代码在内存中的开始地址。另外,一定要注意,函数指针要用 type (*FunctionPtr) 的形式,不要写成 type *FunctionPtr的形式,后者表示返回一个所指类型的指针。
上代码:
include <iostream>
using namespace std;
void Function();
void testFunction(void (*)());
int main()
{
testFunction(Function);
return 0;
}
void Function()
{
cout<<"你好!";
}
void testFunction(void (*Function)())
{
(*Function)();//一定要注意,这里的()不要省略!
}
函数指针数组理解起来就比较容易,但是要注意,数组所指向的所有函数都要有相同类型的返回值和相同的参数类型。
看代码:
include <iostream>
using namespace std;
void function0(int);
void function1(int);
void function2(int);
int main()
{
void (*Function[3])(int) = {function0,function1,function2};
int choice;
cout<<"enter a number between 0 to 2,and you can enter 3 to end"<<endl;
cin>>choice;
while(choice>=0&&choice<=2)
{
(*Function[choice])(choice);
cout<<"continue"<<endl;
cin>>choice;
}
return 0;
}
void function0(int a)
{
cout<<"You chose function0 and entered "<<a<<endl;
}
void function1(int a)
{
cout<<"You chose function1 and entered "<<a<<endl;
}
void function2(int a)
{
cout<<"You chose function2 and entered "<<a<<endl;
}