C/C++的指针4

1.指针函数

#include<iostream>
using namespace std;
//指针函数

int* func() {

	return NULL;
}
int* getArray(int a, int d, int n) {
	int* ret = new int[n];  //动态分配了一个包含 n 个整数的数组
	//ret[0] =a;
	//ret[1] =a+d;
	//...
	//ret[i] =a+i*d;
	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;
}

2.函数指针

指针函数被赋值的函数,需要满足返回值相同和传参个数相同

#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);
	//ptr = func1;   错误
	// 指针函数被赋值的函数,需要满足返回值相同和传参个数相同
	ptr1 = func1;
	ptr1(1, 2);
	return 0;
}

3.函数指针类型定义

3.1函数指针的定义

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

3.2函数指针类型的定义

//函数指针的类型定义
typedef void (*ptr2)(int a, int b, int c, float d, char e);

调用的区别

int main() {
	ptr1 = func1;
	ptr1(1, 2, 3, 4, 5);
    ptr3 = func1;
    ptr3(1, 2, 3, 4, 5);
	ptr2 ptr = func1;  //通过类型来定义函数指针,自定义
	//类似于int a= 6;
	ptr(5, 6, 7, 8, 9);
	return 0;
}

4.函数指针数组

[函数指针1,函数指针2,......]

两种定义方法


typedef void (*fptrs[])(int a, int b, int c, float d, char e);
typedef void (*fptr)(int a, int b, int c, float d, char e);
void func1(int a, int b, int c, float d, char e) {
	cout << "func1" << endl;
}
void func2(int a, int b, int c, float d, char e) {
	cout << "func2" << endl;
}
void func3(int a, int b, int c, float d, char e) {
	cout << "func3" << endl;
}

调用的区别

int main() {

	//int a[] ={1, 2, 3};
	fptrs ptr = { func1,func2,func3 };
	cout << ptr[0] << endl;
	cout << ptr[1] << endl;
	cout << ptr[2] << endl;
	cout << ptr[3] << endl;
	cout << "---------" << endl;
	fptr ptr2[] = {func1,func2,func3};
	cout << ptr2[0] << endl;
	cout << ptr2[1] << endl;
	cout << ptr2[2] << endl;
	return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值