ttyule1 发表于 2020-6-21 18:54:58

C++实验题求教!!

本帖最后由 ttyule1 于 2020-6-21 19:15 编辑

定义一个学生类,它包含学号(int)、姓名(string)、性别(sex)、分数(float)等数据成员,定义一个对象,重载赋值运算符“=”,使“=”能够实现int、string、float型的数据为该对象赋值;重载运算符“<<”“>>”,使之能够直接输入、输出学生类的对象。
如题,是一道实验题,关键就是重载运算符“=”这一块,没太明白是什么意思,请大家帮忙解决一下!!!

下面是除了“重载赋值运算符“=”,使“=”能够实现int、string、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 &);
};

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

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

ttyule1 发表于 2020-6-21 19:12:45

各位大佬帮帮忙!

sunrise085 发表于 2020-6-21 20:01:43

#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;
}
页: [1]
查看完整版本: C++实验题求教!!