指针函数等

指针函数

指针函数返回的是一个地址(指针)。

#include<iostream>
using namespace std;

int* getArray(int a, int d, int n) {
	int* ret = new int[n];
	for (int i = 0; i < n; i++) {
		ret[i] = a + i * d;
	}
	return ret;
}
int main() {
	int* ans = getArray(5, 3, 6);
	for (int i = 0; i < 6; i++) {
		cout << *(ans + i) << endl;
	}
	for (int i = 0; i < 6; i++) {
		cout << ans[i] << endl;
	}
	return 0;
}

函数指针

函数类型 (*指针名)(传入形参){

}

函数类型 函数名(传入形参){

}

在调用函数指针时指针名 = 函数名即可。

#include<iostream>
using namespace std;

double (*ptr)(int a, int b, int c);
void (*ptr1)(int a, int b);
double func(int a, int b, int c) {
	cout << a << "," << b << "," << c << endl;
	return 0.0;
}

void func1(int a, int b) {
	cout << a << "," << b << endl;
}
int main() {
	ptr = func;
	ptr(4, 5, 6);
	ptr1 = func1;
	ptr1(5, 6);
	return 0;
}

函数指针的类型定义

typedef 指针名(传入形参);

#include<iostream>
using namespace std;

void (*fptr1) (int a, int b, int c, float d, char e);
void (*fptr2) (int a, int b, int c, float d, char e);

void func1(int a, int b, int c, float d, char e) {
	cout << a << " " << b << " " << c << " " << d << " " << e << endl;
}

typedef void (*fptr)(int a, int b, int c, float d, char e);
int main() {
	fptr1 = func1; 
	fptr1(1, 2, 3, 4, '5');
	
	fptr2 = func1;
	fptr2(9, 8, 7, 6, '5');

	fptr fp1 = func1;
	fp1(7, 6, 5, 4, '3');
	return 0;
}

函数指针数组

类似正常定义数组

typedef 函数类型 (指针名[数组长度])(传入形参)

#include<iostream>
using namespace std;

typedef void (*fptrs[3])(int a, int b, double c, float d, char e);
typedef void (*fptr)(int a, int b, double c, float d, char e);

void func1(int a, int b, double c, float d, char e) {
	cout << func1 << endl;
}

void func2(int a, int b, double c, float d, char e) {
	cout << func2 << endl;
}

void func3(int a, int b, double c, float d, char e) {
	cout << func3 << endl;
}
int main() {
	fptrs fps = { func1, func2, func3 };
	cout << fps[0] << endl;
	cout << fps[1] << endl;
	cout << fps[2] << endl;

	fptr fp[] = { func1, func2, func3 };
	cout << fp[0] << endl;
	cout << fp[1] << endl;
	cout << fp[2] << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值