/*
以前学过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;
}
学点C++笔记 10 :模板函数
最新推荐文章于 2022-04-21 18:26:37 发布
本文介绍了C++中的模板函数,通过示例展示了如何使用模板实现不同数据类型之间的比较,并讨论了如何重载>、==和<运算符,以便于比较包括自定义类型如Student在内的各种对象。作者通过一个实际的例子演示了模板函数和运算符重载在简化代码复用方面的作用。
摘要由CSDN通过智能技术生成