【sy4_多态的应用_3_输入输出运算符重载】

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;
}
运行结果:

image-20220928125158147

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值