C++Primer plus 例题
2014-11-12 10:31
274 查看
本次是讲解的函数指针的运用,不过我之前还没用过,在这跟大家分享下。
通常,要声明指向特定类型的函数的指针,可以首先编写这种函数的原型然后用(*pf)替换函数名,这样pf就是这类函数的指针。
例如 double pam(int );
double (*pf)(int);在这就是讲pam替换为了(*pf),而pf就是这类函数的指针。
2.获取函数的地址
获取函数地址很简单,只要使用函数名(后面不跟参数)就可以。如果跟参数的话,就是将其返回值传递了。
实例代码如下:
#include "stdafx.h"
#include<iostream>
using namespace std;
double betsy(int);
double pam(int);
void estimate(int lines,double (*pf)(int));
int _tmain(int argc, _TCHAR* argv[])
{
int code;
cout<<"How many lines of code do you need ?";
cin>>code;
cout<<"Here's Betsy's estimate:"<<endl;
estimate(code,betsy);
cout<<"Here's Pam's estimate:"<<endl;
estimate(code,pam);
system("pause");
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 lines,double (*pf)(int))
{
cout<<lines<<"lines will take ";
cout<<(*pf)(lines)<<" hour(s)"<<endl;
}
通常,要声明指向特定类型的函数的指针,可以首先编写这种函数的原型然后用(*pf)替换函数名,这样pf就是这类函数的指针。
例如 double pam(int );
double (*pf)(int);在这就是讲pam替换为了(*pf),而pf就是这类函数的指针。
2.获取函数的地址
获取函数地址很简单,只要使用函数名(后面不跟参数)就可以。如果跟参数的话,就是将其返回值传递了。
实例代码如下:
#include "stdafx.h"
#include<iostream>
using namespace std;
double betsy(int);
double pam(int);
void estimate(int lines,double (*pf)(int));
int _tmain(int argc, _TCHAR* argv[])
{
int code;
cout<<"How many lines of code do you need ?";
cin>>code;
cout<<"Here's Betsy's estimate:"<<endl;
estimate(code,betsy);
cout<<"Here's Pam's estimate:"<<endl;
estimate(code,pam);
system("pause");
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 lines,double (*pf)(int))
{
cout<<lines<<"lines will take ";
cout<<(*pf)(lines)<<" hour(s)"<<endl;
}
相关文章推荐
- C++ primerplus 第12章课本上例题
- [c++ primer plus]使用cout格式化输出
- [c++ primer plus]常用的const及const的语意
- C++ Primer Plus 第四章 复合类型
- C++ Primer Plus 读书笔记 (1 -2 章)
- 《C++.Primer.Plus》学习笔记(二)
- 《c++ primer plus》学习笔记
- C++ Primer Plus 第五版 第六章 编程练习 7
- [学习笔记][C++Primer Plus]使用cout格式化输出字符串
- C++ Primer Plus 第二章 开始学习C++
- C++ Primer Plus 第五版中文版 第六章 编程练习6
- [c++ primer plus]main()执行之前
- C++ primer plus
- C++ Primer Plus 第三章 处理数据
- C++ primer plus 5章9题
- [c++ primer plus]使用标准流格式化输入
- [c++ primer plus]c++ 函数模版,类模版,实例化,具体化,模版作参数,模版的友元
- C++ primer plus 第五版 学习笔记 5章7题
- [学习笔记][C++Primer Plus]String类的使用
- 《C++.Primer.Plus》学习笔记(一)