【C++ 基础 11】 函数指针总结

在家学习的效率真是惨不忍睹。。

===========================

1 指针函数

int* f(int a, int b);
返回一个指向int类型的指针。

2 函数指针

2.1 声明

返回类型 (*函数名)(参数列表);

2.2 示例

int max(int a, int b) {  return a > b ? a : b;  }  
int min(int a, int b) {  return a < b ? a : b;  }  
  
int (*f)(int, int); // 声明函数指针f,指向返回值类型为int,有两个参数类型都是int的函数  
  
void main()  
{  
    f = max; // 函数指针f指向求最大值的函数max  
    int c = (*f)(1, 2);  
    printf("The max value is %d \n", c);  // 2
  
    f = min; // 函数指针f指向求最小值的函数min  
    c = (*f)(1, 2);  
    printf("The min value is %d \n", c);  // 1

    return ;  
}

3 typedef简化函数指针

一般我们会经常使用typedef来简化函数指针的调用。

3.1 声明

typedef 返回类型 (*函数指针类型名)(函参列表);

typedef是定义新的类型,定义这种类型为指向某种函数的指针。

3.2 示例

int max(int a, int b) {  return a > b ? a : b;  }  
int min(int a, int b) {  return a < b ? a : b;  }  

//定义Func类型,Func是指向 返回int且参数为2个int的函数 的指针
typedef int (*Func)(int,int);

void main()  
{  
	Func pFunc = NULL; //声明变量pFunc
	pFunc = &max;      //或者pFunc = max两种写法 
	int c = pFunc(1,2);
	printf("The max value is %d \n", c);  // 2
	return ;  
}  

4 类成员函数指针

类成员包含静态和非静态函数,静态跟对象无关。

4.1 非静态成员函数声明

typedef 返回类型 (类名::*函数指针类型名)(函参列表);

4.2 静态成员函数声明(和一般函数指针一样)

typedef 返回类型 (*函数指针类型名)(函参列表);

4.3 示例

class A{
public:
	int max(int a, int b) {  return a > b ? a : b;  }  
	static int min(int a, int b) {  return a < b ? a : b;  }  
};

typedef int (A::*ClassFunc)(int,int);//类成员函数指针定义
typedef int (*StaticFunc)(int,int);  //静态函数指针定义(和普通的函数指针相同)

void main()  
{  
	/*
	 *  类成员函数指针
	 */
	ClassFunc pClassFunc = &A::max; //类成员函数必须加&符号,否则报错
	//写法1
	A a;
	int c = (a.*pClassFunc)(3,6);
	cout<<c<<endl; //6
	//写法2
	A* pA = &a;      
	c = (pA->*pClassFunc)(3,6);
	cout<<c<<endl; //6

	/*
	 *  静态成员函数指针
	 */
	StaticFunc pStaticFucn = &A::min; //可加&,可不加
	c = pStaticFucn(3,6);
	cout<<c<<endl; //3
}  



转载于:https://www.cnblogs.com/fzll/p/3954578.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值