C++模板【定义学生类包含姓名和成绩两个数据成员,重载比较运算符(按成绩和按姓名两个模式比较)和输出运算符】
实现下列功能。
1)定义学生类包含姓名和成绩两个数据成员,重载比较运算符(按成绩和按姓名两个模式比较)和输出运算符。
2)实现greater_than函数模板,用于比较两个对象的大小,如果a>b,返回true,否则返回false。
3)实现less_than函数模板,用于比较两个对象的大小,如果a<b,返回true,否则返回false。
4)实现Print函数模板,用于打印一维数组。
5)实现冒泡排序的函数模板,输入参数是数组、数组大小和用于比较的数组元素的函数指针。
void bubble_sort(T arr[], int len, bool(*compare)(T&, T&));
//学生类部分
enum SortType{
BY_SCORE,BY_NAME
};
static SortType sort_type ;
class Student{
public:
Student(string name, int score):name_(name),score_(score){
}
bool operator > (const Student& rhs){
if(sort_type == BY_SCORE){
if(score_>rhs.score_){
return true;
}
return false;
}
else if(sort_type == BY_NAME){
if(name_>rhs.name_){
return true;
}
return false;
}
}
bool operator < (const Student& rhs){
if(sort_type == BY_SCORE){
if(score_<rhs.score_){
return true;
}
return false;
}
else if(sort_type == BY_NAME){
if(name_<rhs.name_){
return true;
}
return false;
}
}
//重载输出运算符
friend ostream& operator<<(ostream& os,Student& student){
os<<"["<<student.name_<<","<<student.score_<<"]";
}
private:
string name_;
int score_;
};
// 模板函数部分
template<class T>
bool greater_than(T& a,T& b){
if(a>b){
return true;
}
return false;
}
template<class T>
bool less_than(T& a,T& b){
if(a<b){
return true;
}
return false;
}
template<class T>
void Print(T t[],int len){
for(int i = 0;i<len;i++){
cout<<t[i]<<" ";
}
cout<<endl;
}
template<class T>
void bubble_sort(T arr[],