有如下定义的基类Person: 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函数的函数体。
时间: 2023-07-14 18:12:39 浏览: 204
(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 ofs(filename, ios::binary);
if (!ofs)
{
cerr << "Failed to open the file!" << endl;
exit(1);
}
for (int i = 0; i < n; i++)
{
ofs.write((char*)&stud[i], sizeof(Student));
}
ofs.close();
}
```
(3)从文件中读取所有Student类对象的readFile函数的函数体:
```
void readFile(string filename, Student stud[], int n)
{
ifstream ifs(filename, ios::binary);
if (!ifs)
{
cerr << "Failed to open the file!" << endl;
exit(1);
}
for (int i = 0; i < n; i++)
{
ifs.read((char*)&stud[i], sizeof(Student));
}
ifs.close();
}
```
阅读全文
相关推荐

















