重载函数、函数模板、函数指针的联系和使用

重载函数

重载函数指拥有相同的函数名称,但参数列表不相同(可能是参数类型不相同,可能是参数个数不相同).编译器在编译是通过将调用者提供的实际参数和每一个重载函数的参数对比,找出其中最合适的函数进行执行。

下面我们实现一个重载函数max(),让它接受一下参数:(a):两个整数,(b):两个浮点数,©:一个整形vector,(d):一个浮点型vector,最后编写main()函数测试这下函数。

#include<string>
#include<vector>
using namespace std;

void max(int,int);
void max(double,double);
void max(const vector<int>&);
void max(const vector<double>& );


void max(int num1,int num2)
{
	int max_num	= num1>num2?num1:num2;
	cout<<max_num<<endl;
}
void max(double num1,double num2)
{
	int max_num = num1>num2?num1:num2 ;
	cout<<max_num<<endl;
}

void max(const vector<int> &vec)
{
	int max_num = 0;
	int len = vec.size();
	for(int i= 0;i<len;i++)
		if(max_num < vec.at(i))
			max_num = vec.at(i);
	cout<<max_num<<endl;
}
void max(const vector<double> &vec)
{
	double max_num = 0.0;
	int len = vec.size();
	for(int i= 0;i<len;i++)
		if(max_num < vec.at(i))
			max_num = vec.at(i);
	cout<<max_num<<endl;
}
int main()
{
	vector<int> vec_Int;
	vector<double> vec_Double;
	vec_Int.push_back(1);
	vec_Int.push_back(2);
	vec_Double.push_back(3.0);
	vec_Double.push_back(5.0);
	max(12,11);
	max(14.0,100.0);
	max(vec_Int);
	max(vec_Double);
	return 0;
}

函数模板

同一个函数名称,但里面的参数不一样就要写这么多代码是不是太低效率了,人类永远追求高效(其实是懒),C++设计了一个函数模板来解决这个问题。function template 以关键字template开场,其后紧接着以成对尖括号<>包括起来的一个或多个表示符。这些表示符用来表示我们希望推迟决定的数据类型。用户每利用一次模板,都必须提供确实的类型信息。这些标示符事实上扮演这占位符的角色,用来放置函数参数列表及函数体中某些实际数据类型

#include<string>
#include<vector>
using namespace std;

template <typename T>  //T开始从这里生效
void mymax(T m1 , T m2)
{
	T m_max ;
	m_max = m1 > m2 ? m1 :m2;
	cout << m_max<<endl;
}                                    //从这里失效
template <typename T>                     //这个T和上个T是两个,它们的作用域仅在与它相邻的函数
void mymax(const vector<T> &vec)
{
	if(vec.size()<=0)
		cout<<"数据为空"<<endl;
	T m_max = vec.at(0) ;
	int len = vec.size();
	for(int i=0;i< len;i++)
		if(m_max < vec.at(i))
			m_max = vec.at(i);
	cout<<m_max<<endl;
}


int main()
{
	vector<int> vec_Int;
	vector<double> vec_Double;
	vec_Int.push_back(1);
	vec_Int.push_back(2);
	vec_Double.push_back(3.0);
	vec_Double.push_back(4.0);
	mymax(2,5);
	mymax(5.0,3.0);
	mymax(vec_Int);
	mymax(vec_Double);
	return 0;
}

这里将max()函数名改为了mymax(),原因是标准空间中已经有个max了,如果存在两个max会导致编译器不知道该使用那个。另外需要注意的是函数模板的作用域,它的作用域是紧跟自己的函数。

函数指针

函数指针必须知名所指函数的返回类型及参数列表,如下所示:

void (*funcall)(int ,int);
假设有两个函数min()和max(),我将使用函数指针调用这两个函数。

using namespace std;
void max(int,int);
void min(int,int);

void max(int num1,int num2)
{
	int max = 0;
	max = num1>num2?num1:num2;
	cout << max<<endl;
}
void min(int num1,int num2)
{
	int min = 0 ;
  	min = num1>num2?num2:num1;
	cout<<min<<endl;
}

int main()
{
	void (*pFuncall)(int,int);  //定义函数指针
	pFuncall = max;
	(*pFuncall)(2,3);
	pFuncall= min;
	(*pFuncall)(4,5);
	return 0;
	
}

更为简洁的一种写法是使用typedef定义一种新类型 ,如:

typedef void (*pFuncall)(int,int)
这样就可以将函数指针当作像char、int一样使用了.

总结

在实际的编程中具体使用那种方式实现简洁的代码,需要根据项目要求和实际情况而定,函数模板使函数参数具有可替代性,函数指针则更具有灵活性。

猜你喜欢

转载自blog.csdn.net/Leader_wang/article/details/82764219