Essais: Notes sur la surcharge des opérateurs d'entrée et de sortie

Remarques sur la surcharge des opérateurs d'entrée et de sortie

Les opérateurs d'entrée et de sortie surchargés doivent être écrits sous la forme "Friend Function"

Exemple:

#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;
}

Exécutez la démo:

Insérez la description de l'image ici

Je suppose que tu aimes

Origine blog.csdn.net/qq_44274276/article/details/106942820
conseillé
Classement