#include <iostream>
using namespace std;
class student
{
friend class handler;
friend bool operator>(student& stu1, student& stu2);
friend ostream& operator<<(ostream& cout, const student& stu);
private:
string name;
int score;
public:
int display()
{
return this->score;
}
student(string name =" ", int score = 0) :name(name), score(score) {}
void input(string name, int score)
{
this->name = name;
this->score = score;
}
};
bool operator>(student& stu1, student& stu2)
{
return stu1.score > stu2.score ? true : false;
}
ostream& operator<<(ostream& cout, const student& stu) //重载左移运算符
{
cout << stu.name << " " << stu.score << endl;
return cout;
}
class handler
{
friend ostream& operator<<( ostream& cout, const student& stu);
private:
student* stu;
int size;
public:
handler(int size) : size(size), stu(new student[size]){}
~handler()
{
delete[] stu;
}
void bubble()
{
for (int i = 0; i < this->size - 1; i++)
{
for (int j = 0; j < this->size - 1 - i; j++)
{
if (stu[j] > stu[j + 1]) //重载 >号
{
student temp = stu[j];
stu[j] = stu[j + 1];
stu[j + 1] = temp;
}
}
}
}
void input_hand(string name, int score,int pos)
{
this->stu[pos].name = name;
this->stu[pos].score = score;
}
int handsize()
{
return this->size;
}
void myprint(int pos)
{
//cout << this->stu[pos].name << " " << this->stu[pos].score << endl;
cout << this->stu[pos]; // == operator<<(cout, stu[0])
}
};
int main()
{
handler hand(5);
hand.input_hand("aaa", 100, 0);
hand.input_hand("bbb", 123, 1);
hand.input_hand("ccc", 90, 2);
hand.input_hand("ddd", 110, 3);
hand.input_hand("eee", 112, 4);
hand.bubble();
for (int i = 0; i < hand.handsize(); i++)
{
hand.myprint(i);
}
return 0;
}
用类嵌套的方式对学生类进行排序
最新推荐文章于 2024-10-15 16:38:57 发布