学点C++笔记 10 :模板函数

/*
	以前学过C语言,现在学点C++ ,记录一下
	所有代码均在DEV C++ 5.15 下测试通过
*/

#include <iostream>
using namespace std;

/*
	本次学习模板函数
*/

#define LEFT_BIG_RIGHT 1
#define LEFT_SMALL_RIGHT 2
#define LEFT_EQUAL_RIGHT 0

// 写一个判断两个整数大小的函数
/*
int Compare(const int &a, const int &b ) {
	if (a > b )
		return LEFT_BIG_RIGHT;
	if (a < b)
		return LEFT_SMALL_RIGHT;
	else
		return LEFT_EQUAL_RIGHT;

}
*/
// 如果要判断其他类型的,如 double 的两个数大小,就要再写一个类似的函数
// int Compare(const double &a, const double &b ) 
// 如果还有几十类型,例如下面的Student ,那是多么无趣的重复工作啊。
// 好在C++ 有模板函数
struct Student {
	int ID;
	double CHN;
	double ENG;
	double MAT;

};
// 比较两个学生总成绩大小
/*
int Compare(const Student &stu1, const Student &stu2) {
	double r1, r2, r;
	r1 = stu1.CHN + stu1.ENG + stu1.MAT;
	r2 = stu2.CHN + stu2.ENG + stu2.MAT;
	r = r1 - r2;
	if (r > -0.001)
		&& (r < 0.001)
		return LEFT_EQUAL_RIGHT;
	if (r > 0.001)
		return LEFT_BIG_RIGHT;
	else
		return LEFT_SMALL_RIGHT;

}
*/
// 重载 > 运算符
bool operator>(const Student &stu1, const Student &stu2) {
	double r1, r2, r;
	r1 = stu1.CHN + stu1.ENG + stu1.MAT;
	r2 = stu2.CHN + stu2.ENG + stu2.MAT;
	r = r1 - r2;
	if (r > 0.001)
		return true;
	else
		return false;


}

// 重载 == 运算符
bool operator==(const Student &stu1, const Student &stu2) {
	double r1, r2, r;
	r1 = stu1.CHN + stu1.ENG + stu1.MAT;
	r2 = stu2.CHN + stu2.ENG + stu2.MAT;
	r = r1 - r2;
	if ((r >  -0.001) && (r < 0.001))
		return true;
	else
		return false;

}

//重载 < 运算符
bool operator<(const Student &stu1, const Student &stu2) {
	double r1, r2, r;
	r1 = stu1.CHN + stu1.ENG + stu1.MAT;
	r2 = stu2.CHN + stu2.ENG + stu2.MAT;
	r = r1 - r2;
	if (r < - 0.001)
		return true;
	else
		return false;

}


//使用模板函数进行比较
template<class T>
int Compare(const T &a, const T &b ) {
	if (a > b )
		return LEFT_BIG_RIGHT;
	if (a < b)
		return LEFT_SMALL_RIGHT;
	else
		return LEFT_EQUAL_RIGHT;
}

int main(int argc, char **argv) {
	int a = 10, b = 20;
	double c = 20.2, d = 30.1;
	int r;
	Student stu2 = {10, 89.5, 67.7, 88.8};

	Student stu1 = {11, 97.5, 88.6, 59.9};
	cout << "stu1 score total: " << stu1.CHN + stu1.ENG + stu1.MAT << endl;
	cout << "stu2 score total: " << stu2.CHN + stu2.ENG + stu2.MAT << endl;
	cout << "Compare(stu1, stu2)=" << Compare(stu1, stu2) << endl;
	cout << "Compare(10,20)=" << Compare(10, 20) << endl;
	cout << "Compare(20.2,30.1)=" << Compare(20.2, 30.1) << endl;

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值