sy4_多态的应用_3_输入输出运算符重载
(3) 使用实验一中设计的Student类,其中至少包括四个数据成员,如果不足四个可补充新的数据成员,编程实现对插入符(<<)和提取符(>>)的重载,使它们能够对Student类的对象直接进行输人和输出,在主函数中进行测试。
实现思路:
C++ 能够使用流提取运算符 >> 和流插入运算符 << 来输入和输出内置的数据类型。可以重载流提取运算符和流插入运算符来操作对象等用户自定义的数据类型。我们需要把运算符重载函数声明为类的友元函数,这样我们就能不用创建对象而直接调用函数。
运算符重载函数友元声明
friend istream& operator>>(istream&,Student&)
friend ostream& operator<<(ostream&,Student&)
输入、输出运算符重载函数的实现
istream& operator>>(istream &input, Student &stud)
{
input >> stud.id >> stud.name >> stud.sex >> stud.score;
return input;
}
ostream& operator<<(ostream &output, Student &stud)
{
output << "学号:" << stud.id <<" " << " 姓名:" << stud.name << " " << "性别:" << stud.sex << " " << "成绩:" << stud.score << endl;;
return output;
}
整段代码:
#include <iostream>
using namespace std;
class Student
{
private:
string id;
string name;
string sex;
float score;
public:
friend istream& operator>>(istream &, Student &);
friend ostream& operator<<(ostream &, Student &);
};
istream& operator>>(istream &input, Student &stud)
{
input >> stud.id >> stud.name >> stud.sex >> stud.score;
return input;
}
ostream& operator<<(ostream &output, Student &stud)
{
output << "学号:" << stud.id <<" " << " 姓名:" << stud.name << " " << "性别:" << stud.sex << " " << "成绩:" << stud.score << endl;;
return output;
}
int main()
{
Student stud1, stud2;
cout << "请输入学生学号、姓名、性别、分数信息:" << endl;;
cin >> stud1;
cout << "学生信息为:" << endl;
cout << stud1;
return 0;
}