class Person {public: Person(char name[]="XXX", char sex='M',int age=18) { strcpy(this->name,name); this->sex =sex; this->age = age; } virtual void input() { cout << "Enter name:"; cin>> name; cout << "Enter sex:"; cin >> sex; cout << "Enter age:"; cin >> age; } virtual void output() { cout << "name:"<<name << "\t"; cout << "sex:"<< sex << "\t"; cout << "age:"<< sex << age <<endl; } protected: char name[21]; char sex; int age; }; 由Person类派生出如下的派生类Student: class Student:public Person {public: Student(char name[]="XXX", char sex='M',int age=18,char num[]="000000",char class_name[]="XXXXXX"); void input(); void output(); private: char num[10]; //学号 char class_name[21];//班级 }; void writeFile(string filename,Student stud[],int); void readFile(string filename,Student stud[],int); 要求: (1)写出Student类的构造函数、input函数、output函数的类外定义。 (2)写出把一组Student类对象写入文件的writeFile函数的函数体。 (3)写出从文件中读取所有Student类对象的readFile函数的函数体。
时间: 2024-01-14 15:03:02 浏览: 247
(1) Student类的构造函数、input函数、output函数的类外定义如下:
```
Student::Student(char name[], char sex, int age, char num[], char class_name[]) : Person(name, sex, age) {
strcpy(this->num, num);
strcpy(this->class_name, class_name);
}
void Student::input() {
Person::input();
cout << "Enter student number:";
cin >> num;
cout << "Enter class name:";
cin >> class_name;
}
void Student::output() {
Person::output();
cout << "student number:" << num << "\t";
cout << "class name:" << class_name << endl;
}
```
(2) 把一组Student类对象写入文件的writeFile函数的函数体如下:
```
void writeFile(string filename, Student stud[], int n) {
ofstream out(filename, ios::out | ios::binary);
if (!out) {
cout << "Cannot open file!" << endl;
return;
}
out.write(reinterpret_cast<char*>(&n), sizeof(int));
for (int i = 0; i < n; i++) {
out.write(reinterpret_cast<char*>(&stud[i]), sizeof(Student));
}
out.close();
}
```
(3) 从文件中读取所有Student类对象的readFile函数的函数体如下:
```
void readFile(string filename, Student stud[], int n) {
ifstream in(filename, ios::in | ios::binary);
if (!in) {
cout << "Cannot open file!" << endl;
return;
}
int count;
in.read(reinterpret_cast<char*>(&count), sizeof(int));
if (count != n) {
cout << "The number of records in the file does not match the input!" << endl;
in.close();
return;
}
for (int i = 0; i < n; i++) {
in.read(reinterpret_cast<char*>(&stud[i]), sizeof(Student));
}
in.close();
}
```
阅读全文