函数指针typedef

函数指针typedef

基本结构

typedef 数据类型 (*类型名)(参数类型);//定义了一个函数指针类型
类型名 指针名 = 函数名;//定义了一个类型名下的指针指向函数;

如:

int sum(int a,int b){
	return a + b;
}
typedef int (*operation)(int,int);//定义了一个operation型的函数指针类型
operation a = sum;//定义了一个operation类型的指针a,指向sum函数
int main(){
	cout << a(2,5);//使用a来调用函数sum,实参为2和5,返回值为7
}
void test(){
	cout << "test" << endl;
}
typedef void (*LP)();
LP p = test;
int main(){
	p();
}

函数指针数组

基本结构
typedef 数据类型 (*类型名)(参数类型);//定义了一个函数指针类型
类型名 指针名[] = {函数名1,函数名2...};//定义了一个类型名下的指针指向函数;
程序案例
#include<iostream>
using namespace std;
void t1() { cout << "test1"; }
void t2() { cout << "test2"; }
void t3() { cout << "test3"; }
void t4() { cout << "test4"; }
void t5() { cout << "test5"; }
typedef void(*LP)();
int main() {
	LP a[] = { NULL,t1,t2,t3,t4,t5 };
	int x;
	cin >> x;
	a[x]();
	return 0;
}
#include<iostream>
using namespace std;
int sum(int a, int b) { return a + b; }
int poor(int a, int b) { return a - b; }
int times(int a, int b) { return a * b; }
int devide(int a, int b) { return a / b;}
typedef int (*operation)(int, int);
int main() {
	operation p[] = { times,sum,NULL,poor,NULL,devide };
	int a, b;
	char symbol;
	cin >> a >> symbol >> b;
	cout << p[symbol - 42](a, b);
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值