指针函数
返回指针的函数
int* array_() {
int* ptr = (int*)malloc(10 * sizeof(int));
for (int i = 0; i < 10; i++) {
*(ptr + i) = 10;
}
return ptr;
}
int main() {
int* temp = array_();
for (int i = 0; i < 10; i++) {
cout << *(temp + i) << " ";
}
cout << endl;
return 0;
}
10 10 10 10 10 10 10 10 10 10
函数指针
声明函数指针
// 声明一个函数指针
void (*foo) ();
如图所示,函数指针的声明
注意,不要混淆函数指针
和指针函数
int (*fptrl)(int, int); //指向函数的指针
int* function(int, int); //返回指针类型的函数
我们还可以使用 typedef
声明一个类型定义
typedef int (*funcptr)(int,int);//funcptr 为这个类型
funcptr fptr2 = sum;
通过函数指针来调用函数
函数指针存储函数的地址,用于指向函数,可以借由函数指针来调用不同的函数
但是函数指针和其所指向的函数的类型必须一致,也就是说,其返回值类型和参数类型和参数个数需一致
//声明函数指针
typedef int (*function_ptr)(int, int);
//需要被指向的函数
int sum(int a, int b) {
return a + b;
}
int main()
{
//fptrl = sum2;类型不匹配,这个返回的是double类型,接受的也是两个double的参数
function_ptr fptrl = sum;
cout << fptrl(2, 3) << endl; // 5
return 0;
}
在这个案例中,我们使用了函数指针来调用函数,但是我们没有在函数前面加&
,函数名和数组名类似,可以直接返回该函数的地址
int (*fptrl) (int);
int square(int num) {
return num * num;
}
int main()
{
fptrl = square;
cout << fptrl(2) << endl; //4
return 0;
}
这是调用另一个函数的例子,理解一下内存中函数是怎么被调用的
传递函数指针
只要把函数指针声明作为函数参数即可
//声明函数指针
typedef int (*fptrOperation)(int, int);
//加法
int add(int num1, int num2) {
return num1 + num2;
}
//减法
int sub(int num1, int num2) {
return num1 - num2;
}
//接受函数指针,还有用作计算的两个int参数
int compute(fptrOperation operation, int a, int b) {
return operation(a, b);//返回操作的结果
}
int main()
{
cout << compute(add, 5, 6);
cout << compute(sub, 5, 6);
/*fptrOperation fptr = sum;
cout << "the result(+) is: " << compute(add, 10, 5) << endl;
cout << "the result(+) is: " << compute(fptr, 10, 5) << endl;
cout << "the result(+) is: " << evaluate('+', 10, 5) << endl;
fptr = sub;
cout << "the result(-) is: " << compute(sub, 10, 5) << endl;
cout << "the result(-) is: " << compute(fptr, 10, 5) << endl;
cout << "the result(+) is: " << evaluate('-', 10, 5) << endl;*/
return 0;
}
返回函数指针
typedef int (*fptrOperation)(int, int);
//加法
int add(int num1, int num2) {
return num1 + num2;
}
//减法
int sub(int num1, int num2) {
return num1 - num2;
}
//计算
int compute(fptrOperation operation, int a, int b) {
return operation(a, b);
}
//根据字符返回函数指针
fptrOperation select(char opcode) {
switch (opcode) {
case '+': return add;
case '-': return sub;
}
}
//接受字符并调用select函数,接受select返回的函数指针,调用该函数指针指向的函数
int evaluate(char opcode, int num1, int num2) {
fptrOperation operation = select(opcode);
return operation(num1, num2);
}
int main()
{
fptrOperation fptr = add;
cout << "the result(+) is: " << compute(add, 10, 5) << endl;
cout << "the result(+) is: " << compute(fptr, 10, 5) << endl;
cout << "the result(+) is: " << evaluate('+', 10, 5) << endl;
fptr = sub;
cout << "the result(-) is: " << compute(sub, 10, 5) << endl;
cout << "the result(-) is: " << compute(fptr, 10, 5) << endl;
cout << "the result(+) is: " << evaluate('-', 10, 5) << endl;
return 0;
}
看到这里,学过C++的是否觉得有点眼熟,这不就是多态那味嘛~
所以说,打好基础很重要!