C++实验(二)

题目:

  1. 定义一个复数类。重载运算符“+”为成员函数,使之能够用于复数的加法;重载运算符“*”为友元函数,使之能够用于复数的乘法。
  2. 定义一个学生类,它包含学号(int)、姓名(string)、性别(sex)、分数(float)等数据成员,定义一个对象,重载赋值运算符“=”,使“=”能够实现int、string、float型的数据为该对象赋值;重载运算符“<<”“>>”,使之能够直接输入、输出学生类的对象。
#include <iostream>
#include <string>
using namespace std;
 
class Student
{
    private:
        int num;
        string name;
        char sex;
        float score;
    public:
        Student(){}
        Student(int nu,string na,char se='M',float sc=0)
        {
            num=nu;
            name=na;
            sex=se;
            score = sc;
        }
        friend istream & operator >>(istream&,Student &);
        friend ostream & operator <<(ostream&,Student &);  
        Student & operator =(const Student &);
};

istream &operator >>(istream & is ,Student &s )
{
    is>>s.num>>s.name>>s.sex>>s.score;
    return is;
}
ostream &operator <<(ostream & os ,Student &s)
{
    os<<"【学生信息】"<<"学号:"<<s.num<<","<<"姓名:"
		<<s.name<<","<<"性别:"<<s.sex<<","<<"成绩:"<<s.score<<endl;
    return os;
}
Student& Student:: operator =(const Student &stu)
{
    if(this!=&stu)
    {
        this->num=stu.num;
        this->name=stu.name;
        this->sex=stu.sex;
        this->score=stu.score;
    }
    return *this;
}

int main()
{
    Student stu;
    cout<<"请分别输入该学生的学号、姓名、性别和成绩(中间用空格隔开):";
    cin >> stu;
    cout << stu;
    Student stu2;
    stu2=stu;
    cout<<stu2;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jackson Xi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值