C++函数指针(函数作为参数)

本文介绍了C++中的函数指针,包括其构成,如何作为参数传递,以及如何创建函数指针数组。通过实例说明了如何将函数名当作指针,将函数指针作为参数传入函数,实现灵活的函数调用。

1.构成:
所指函数的返回类型 + 指针名 + 所指函数的参数列表

double (*pf)(int);// 指针pf指向的函数, 输入参数为int,返回值为double 

const vector<int>* (*seq_ptr)(int);// 指针seq_ptr指向一个vector类型的指针

2.使用方式:

const vector<int> *pseq = seq_ptr(pos);//赋值调用
const vector<int> *pseq =*seq_ptr)(pos);//推荐使用


double y = (*pf)(5);//推荐使用
double y = (pf)(5)

实例:注意函数名就是指针,将指针作为参数传入即可

#include <stdio.h>
#include <time.h>
#include <iostream>

clock_t start, stop;

double duration;

double f1(int n, double a[], double x)
{
	int i;
	double p = a[0];
	for (i = 1; i <= n; i++)
		p += (a[i] * pow(x, i));
	return p;
}
double f2(int n, double a[], double x)
{
	int i;
	double p = a[n];
	for (i = n; i > 0; i--)
		p += ( a[i-1]+x * p );
	return p;
}

void get_duration(int n, double a[], double x,double(*funtion_ptr)(int n ,double a[],double x))
{
	start = clock();
	
	double p = (*funtion_ptr)(n, a, x);
		
	stop = clock();
	duration = ((double)(stop - start) / CLK_TCK);

	std::cout << "\n tick:" << (double)(stop - start) << "\n"
		<< "second:" << duration << std::endl;
}
const int max = 10;
double f1(int n, double a[], double x);
double f2(int n, double a[], double x);

int main()
{	
	int i;
	double a[max];
	for (i = 0; i < max; i++) 
		a[i] = (double) i; // turn to double for next calculate	
	get_duration(max - 1, a, 1.1, f1);//将f1(函数名即是指针)作为参数传入
	system("pause");
	return 0;
}

3.指针数组
构建一个装有函数的列表,可以用数组的特性来循环或选择

const vector<int>* fibon_seq(int size);
const vector<int>* lucas_seq(int size);
const vector<int>* square_seq(int size);//3种数列除了计算方法别的参数都相同

//seq_array是个数组,内放函数指针
const vector<int>* (*seq_array[])(int) = {fibon_seq,lucas_seq,square_seq}//用数组的特性来循环
int seq_index = 0;
while(next_seq==true)
{
	seq_ptr = seq_array[++seq_index];
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值