简明的C++函数指针学习教程
定义 语法 int (*myFunc)(double b,int c); 说明 函数指针的定义形式中的数据类型是指函数的返回值的类型。 int (*p)(int a,int b);//p是一个指向函数的指针变量,所指函数的返回值类型为整型 int *p(int a,int b);//p是函数名,此函数的返回值类型为整型指针 指向函数的指针变量不是固定指向哪一个函数的,而只是表示定义了一个这样类型的变量,它是专门用来存放函数的入口地址的;在程序中把哪一个函数的地址赋给它,它就指向哪一个函数。 int fn1(int x,int y); int fn2(int x); 定义如下的函数指针: int (*p1)(int a,int b); int (*p2)(int a); 则 p1 = fn1; //正确 p2 = fn2; //正确 p1 = fn2; //产生编译错误 定义了一个函数指针并让它指向了一个函数后,对函数的调用可以通过函数名调用,也可以通过函数指针调用(即用指向函数的指针变量调用)。 函数指针使用举例 #include <iostream> using namespace std; class test { public: test() { cout<<"constructor"<<endl; } int fun1(int a,char c) { cout<<"this is fun1 call:"<<a<<" "<<c<<endl; return a; } void fun2(double d)const { cout<<"this is fun2 call:"<<d<<endl; } static double fun3(char buf[]) { cout<<"this is fun3 call:"<<buf<<endl; return 3.14; } }; int main() { // 类的静态成员函数指针和c的指针的用法相同 double (*pstatic)(char buf[]) = NULL;//不需要加类名 pstatic = test::fun3; //可以不加取地址符号 pstatic("myclaa"); pstatic = &test::fun3; (*pstatic)("xyz"); //普通成员函数 int (test::*pfun)(int,char) = NULL; //一定要加类名 pfun = &test::fun1; //一定要加取地址符号 test mytest; (mytest.*pfun)(1,'a'); //调用是一定要加类的对象名和*符号 //const 函数(基本普通成员函数相同) void (test::*pconst)(double)const = NULL; //一定要加const pconst = &test::fun2; test mytest2; (mytest2.*pconst)(3.33); // //构造函数或者析构函数的指针,貌似不可以,不知道c++标准有没有规定不能有指向这两者的函数指针 // (test::*pcon)() = NULL; // pcon = &test.test; // test mytest3; // (mytest3.*pcon)(); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |