【C++】函数指针基础知识理解和使用--统计代码运行时间的简易程序

版权声明:本文为博主原创文章,未经允许,不得转载!欢迎留言附带链接转载! https://blog.csdn.net/qq_15698613/article/details/89418515

目录

什么是函数地址?

1.假如你有一个需求?改怎么做

1.1 获取函数地址

1.2 声明函数指针 

1.3 使用指针调用函数 

 2. 实现需求的代码


 什么是函数地址?

1.假如你有一个需求?改怎么做

假如你设计一个函数estimate(),用来估算指定行数代码的时间。要将使用的算法函数传递给estimate(),需要以下几步:

1.1 获取函数地址

 

think(),think就是函数的地址。

1.2 声明函数指针 

 注意1:

注意2:

 

void estimate(int line, double (*pf)(int));

1.3 使用指针调用函数 

 2. 实现需求的代码

// fun_ptr.cpp -- 本程序用来示例函数指针
// 输入代码数和函数,能算出时间
#include<iostream>
using namespace std;
double betsy(int);
double pam(int);

void estimate(int line, double(*pf)(int));//注意:特征标,返回类型应该一致!

int main()
{
	int code;
	cout << "多少行代码?" << endl;
	cin >> code;
	cout << "这是老王的结果:" << endl;
	estimate(code, betsy);
	cout << "这是老李的结果:" << endl;
	estimate(code, pam);
	
	return 0;
}

double betsy(int lns)
{
	return 0.05*lns;
}

double pam(int lns)
{
	return 0.03*lns + 0.0004*lns*lns;
}

void estimate(int line, double(*pf)(int))
{
	cout << line << " 行代码需要";
	cout << (*pf)(line) << " 小时" << endl;
}

 运行结果:

猜你喜欢

转载自blog.csdn.net/qq_15698613/article/details/89418515