C++ 函数指针

本文详细介绍了函数指针的概念,包括普通函数指针的声明与使用、通过typedef简化函数指针的声明方式,以及类成员函数指针的声明与使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.函数指针


1.1 声明

int* f(int a, int b);


1.2 示例

#include<iostream>


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 ;  
}


2.typedef简化函数指针


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

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

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

2.2 示例
 

#include<iostream>

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的函数  
typedef int(*Func)(int, int); // typedef定义新的类型Func,指向返回值类型为int,有两个参数类型都是int的函数  

void main()
{
	Func func = max; // 函数指针指向求最大值的函数max  
	int c = func(1, 2);
	printf("The max value is %d \n", c);  // 2

	func = min; // 函数指针指向求最小值的函数min  
	c = func(1, 2);
	printf("The min value is %d \n", c);  // 1

	getchar();
	return;
}


3.类成员函数指针


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

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


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

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


3.3 示例
 

#include<iostream>
using namespace std;

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);  //静态函数指针定义(和普通的函数指针相同)

int 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

	getchar();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值