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