Ostream và istream

Mn giải thích dùm cách hoạt động của ostream và istream cho mình với. Thật sư ngâm cứu mãi ko thể hiểu được

class Student: public Person{
protected:
    char *ID;
    float score;
public:
    Student(char *n="Ho va ten", char *h="Que quan", int b=1990, char *g="female", char *id="ma sinh vien",float s=0);
    ~Student();
     void init();
     void show();
    friend ostream & operator<<(ostream &out, const Student &s);
    friend istream & operator>>(istream &in, Student &s);
    Student & operator=(const Student &s);
};

Student::Student(char *n, char *h, int b, char *g, char *id,float s):Person(n,h,b,g)
{
    int k;
    k = strlen(id);
    ID = new char[k+1];
    strcpy(ID,id);

    score = (s>0)? s:0;
}
Student::~Student()
{
    delete(ID);
}
void Student::init()
{
    cout << "Nhap MSV: ";
    fflush(stdin);
    cin >> ID;

    Person::init();
    cout << "Nhap diem: ";
    cin >> score;
}
void Student::show()
{
    cout << ID << "\t";
    Person::show();
    cout << score << endl;
}
ostream & operator<<(ostream &out, const Student &s)
{
    out << s.ID << "\t";
    out << (Person &)s;
    out << s.score;
    return out;
}
istream & operator>>(istream &in, Student &s)
{
    cout << "Nhap MSV: ";
    fflush(stdin);
    gets(s.ID);

    in >> (Person &)s;

    cout << "Nhap diem: ";
    in >> s.score;

    return in;
}
Student & Student::operator=(const Student &s)
{
    Person::operator=(s);

    int k;
    k = strlen(s.ID);
    ID = new char[k+1];
    strcpy(ID,s.ID);

    score = s.score;
    return *this;
}

Bạn xem lại phần toán tử: https://en.cppreference.com/w/cpp/language/operators

Giả sử bây giờ tạo:
Student hocsinh1;

Sau đó: std::cin >> hocsinh1 thì thế nào?

2 Likes

xem rồi nhưng mình vẫn ko hiểu được :frowning:

@Tran_Hai_Anh Những điều bạn cần làm rõ:
1/ Nạp chồng toán tử (operator overloading).
2/ Tham số &in là một tham chiếu đến đến một std::istream https://en.cppreference.com/w/cpp/io/basic_istream

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?