#include
using namespace std;
double func(int a)
{
cout<<a<<endl;
}
int main()
{
double (*p)(int);
p = func;
p(10);
}
// 输出10
或用typedef定义
#include
using namespace std;
typedef double (*P)(int);
double func(int a) {
cout<<a<<endl;
}
int main()
{
P p=func;
p(10);
// (*p)(10) //结果一样
}
// 输出10
/*
* 下面这个例子是说,func里面要传递不同的参数,但是在执行里面代码之前,要先判断传进来的参数的大小
* 如果把函数模板放入两个函数,然后进行重载,会出现代码的部分冗余,因此这里考虑用模板把公共操作提出来
*/
#include
#include
#include
using namespace std;
// 定义一个函数模板
template<typename T>
int compare(const T &t1, const T &t2){
return t1>t2? 1: 0;
}
// 两个同名的函数,第一个参数都是函数指针
void func(int(*F)(const int&a, const int&b), int a, int b){
if(F(a, b)) cout<<"int 1"<<endl;
else cout<<"int 2"<<endl;
}
void func(int(*F)(const double&a, const double&b), double a, double b){
if((*F)(a, b)) cout<<"double 1"<<endl;
else cout<<"double 2"<<endl;
}
int main()
{
int a = 10, b = 20;
double c = 30.0, d = 20.0;
func(compare<int>, a, b);
func(compare<double>, c, d);
}
/*
int 2
double 1
*/
/*
* 下面这个例子是说,func里面要传递不同的参数,但是在执行里面代码之前,要先判断传进来的参数的大小
* 如果把函数模板放入两个函数,然后进行重载,会出现代码的部分冗余,因此这里考虑用模板把公共操作提出来
*/
#include
#include
#include
#include "new_h.h"
using namespace std;
// 定义一个函数模板
int main()
{
int a = 10, b = 20;
double c = 30.0, d = 20.0;
func(compare<int>, a, b);
func(compare<double>, c, d);
show();
show();
}
/*
int 2
double 1
*/
#ifndef NEW_H_H
#define NEW_H_H
#include
using namespace std;
void show();
#include "learn_temp.cpp"
template <typename T> int compare(const T&, const T&);
void func(int(*F)(const int&a, const int&b), int a, int b);
void func(int(*F)(const double&a, const double&b), double a, double b);
#endif
template <typename T> int compare(const T&a, const T&b){
return a>b?1:0;
}
#include "new_h.h"
void show(){
cout<<"show"<<endl;
}
void func(int(*F)(const int&a, const int&b), int a, int b){
if(F(a, b)) cout<<"int 1"<<endl;
else cout<<"int 2"<<endl;
}
void func(int(*F)(const double&a, const double&b), double a, double b){
if((*F)(a, b)) cout<<"double 1"<<endl;
else cout<<"double 2"<<endl;
}
int 2
double 1
show
show