1、函数指针的定义与使用
#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((char*)"mycall");
pstatic = &test::fun3;
double rtnValue = (*pstatic)((char*)"xyz");
cout<<"rtnValue:"<<rtnValue<<endl;
//普通成员函数:类名与取地址符&必须加
int (test::*pfun)(int, char) = NULL; //声明
pfun = &test::fun1; //赋值
test mytest;
(mytest.*pfun)(1, 'a'); //调用
//const 函数(基本普通成员函数相同)且声明时需加上const
void (test::*pconst)(double)const = NULL;
pconst = &test::fun2;
test mytest2;
(mytest2.*pconst)(3.33);
//构造函数或者析构函数的指针,貌似不可以,不知道c++标准有没有规定不能有指向这两者的函数指针
//(test::*pcon)() = NULL;
//pcon = &test.test;
//test mytest3;
//(mytest3.*pcon)();
return 0;
}
运行结果:
2、函数指针作函数参数
#include <iostream>
using namespace std;
/********普通函数指针作函数参数**************/
void fun(int k, char c)
{
printf("this is fun2 call:%d %c\n", k, c);
}
void fun1(void (*pfun)(int, char), int a, char c)
{
pfun(a, c);
}
void test1()
{
fun1(fun, 1, 'a');
}
/**********成员函数指针作函数参数********/
class A {
public:
void funA(int val)
{
cout<<"call funA and val+1 = "<<val+1<<endl;
}
static void funA1(int val)
{
cout<<"call funA1 and val+1 = "<<val+1<<endl;
}
};
class B{
public:
void funB(A &a,void (A::*p)(int), int val)
{
cout<<"call funB and val = "<<val<<endl;
(a.*p)(val);
}
void funB1(void (*p)(int), int val)
{
cout<<"call funB1 and val = "<<val<<endl;
p(val);
}
};
void test2()
{
A a;
B b;
b.funB(a,&A::funA, 1);
b.funB1(&A::funA1,3);
}
int main()
{
cout<<"普通函数指针:"<<endl;
test1();
cout<<"成员函数指针:"<<endl;
test2();
return 0;
}
运行结果:
3、成员函数指针作为返回值
/*
*asReturn.cpp
*C++函数指针作函数返回值
*/
#include <iostream>
using namespace std;
class A
{
public:
int funA(int a, char c)
{
cout<<"this is fun call:"<<a<<" "<<c<<endl;
return a;
}
};
class B
{
public:
// funB是B 的成员函数
// 函数名 :funB
// 函数参数 :double d
// 函数返回值:指向A的成员函数funA, int(A::*)(int, char)
int (A::*funB(double d))(int, char)
{
cout<<d<<endl;
return &A::funA;//&不可省
//若省去&:invalid use of non-static member function ‘int A::funA(int, char)’
}
};
int main()
{
A a;
B b;
//定义指向类A的funA成员函数的函数指针p(注意:类名不可省)
int (A::*p)(int, char) = b.funB(3.33);
(a.*p)(1, 'a');
//省略类名A
//int (*q)(int, char) = b.funB(3.14);
//报错:error: cannot convert ‘int (A::*)(int, char)’ to ‘int (*)(int, char)’ in initialization
return 0;
}