指针函数
指针函数返回的是一个地址(指针)。
#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;
}