隨筆小記:重載輸入輸出運算符的注意事項

重載輸入輸出運算符的注意事項
重載輸入輸出運算符必須寫成《友元函數》

示例:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

class Student {
private:
	string name;
	int score;
protected:
	friend bool cmp(const Student& s1, const Student& s2);
public:
	Student() {  }
	Student(string name_, int score_) :name(name_), score(score_) {  }
	string getName() const { return this->name; }
	int getScore() const { return this->score; }
	
	friend void StudentSort(const Student stu[], int n);
	friend ostream& operator << (ostream& out, const Student& stu);
	friend istream& operator >> (istream& in, const Student& stu);
};

ostream& operator << (ostream& out, const Student& stu) {
	out << "姓名:" << stu.getName() << " 分數:" << stu.getScore() << endl;
	return out;
}

istream& operator >> (istream& in, Student& stu) {
	string name;
	int score;
	in >> name >> score;
	stu = Student(name, score);
	return in;
}

bool cmp(const Student& s1, const Student& s2) {
	if (s1.score != s2.score)
		return s1.score > s2.score;
	return s1.name < s2.name;
}

void StudentSort(Student stu[], int n) {
	sort(stu, stu + n, cmp);
}

int main() {
	Student stu[3];
	for (int i = 0; i < 3; ++i)
		cin >> stu[i];
	cout << "------------排序前------------" << endl;
	for (int i = 0; i < 3; ++i)
		cout << stu[i];
	StudentSort(stu, 3);
	cout << "------------排序後------------" << endl;
	for (int i = 0; i < 3; ++i)
		cout << stu[i];
	return 0;
}

運行演示:

在這裏插入圖片描述

相關文章
相關標籤/搜索