模板与操作符重载

关于大小的模板函数

#include <iostream>
#include <string>

using namespace std;

template<class U, class V>
bool MyGreater(U &u, V &v)
{
	return u > v;
}

class Student
{
	char name[20];
	int grade;
public:
	Student(char name[], int grade)
	{
		strcpy(this->name, name);
		this->grade = grade;
	}

	bool operator>(const int &value)const	// 重载Student类中的>运算符
	{
		return grade > value;
	}
};

int main()
{
	Student male("XiaoMing", 70);
	int base = 60;
	cout << MyGreater(male, base) << endl;		// u是Student对象,而v是基本数据类型。

	return 0;
}

关于数组二分查找的模板函数

#include <iostream>
#include <string>

using namespace std;

template<class T1, class T2>
int binary_search(T1 t[], int n_size, T2 value)
{
	int left=0, right=n_size-1;
	int mid=0;
	bool flag = false;
	while(left <= right)
	{
		mid = (left+right) >> 1;
		int cur = t[mid];
		if(value==cur)		// 注意重载操作符的顺序,应该是value==
		{
			flag = true;
			break;
		}
		if(value>cur)
			left = mid+1;
		if(value<cur)
			right = mid-1;
	}

	int pos = ((flag==true)?mid:-1);
	return pos;
}

class Student
{
	char name[20];
	int grade;
public:
	Student(char name[], int grade)
	{
		strcpy(this->name, name);
		this->grade = grade;
	}

	bool operator<(const int &value)const
	{
		return grade < value;
	}

	bool operator==(const int &value)const
	{
		return grade == value;
	}

	bool operator>(const int &value)const
	{
		return grade > value;
	}
};

int main()
{
	int arr[] = {1, 4, 6, 7, 10, 17, 19, 24, 32};
	int n_size = 9;
	Student male("XiaoMing", 19);

	int res = binary_search(arr, n_size, male);
	cout << res << endl;

	return 0;
}

由于STL中有大量的模板函数,因此很多时候要重载与之对应的操作符。模板函数相当于已编制好的应用框架,操作符重载相当于调用的接口。

(最近更新:2019年09月08日)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值