类和对象:按下列要求定义一个学生类(Student)。

这篇博客介绍如何在Python中定义一个学生类(Student)及其子类研究生类(Gra_student)。学生类包括_Sno(学号),_Sname(姓名),_Sage(年龄)等属性,并通过属性装饰器进行封装。研究生类(Gra_student)增加了_research(研究方向)属性。文章详细展示了如何实现__str__方法以返回格式化的字符串,同时提供了实例代码,演示了如何创建对象并调用__str__方法来展示学生和研究生的信息。
摘要由CSDN通过智能技术生成

 

按下列要求定义一个学生类(Student),要求:

(1).初始化数据成员数据成员(_Sno,_Sname,_Sage);

(2).通过属性装饰器定义数据成员(Sno,Sname,Sage);

(3).定义特殊方法__str__(self),该方法返回:这样的字符串“我叫张三,学号是1101,年龄为33,是一名学生”,其中张三,1101,33,根据用户的输入来显示。”;

(4).通过继承定义一个研究生类(Gra_student),并增加数据成员研究方向(_research)

(5). 在Gra_student类中,定义特殊方法__str__(self),该方法返回:我叫李四,学号是1102,年龄为35,是一名研究生,研究方向是complex network

使用 C++ 编写代码实现上述要求,示例代码如下:// 定义 Student 类 class Student { public: int num; char name[20]; int score; };// 定义 StudentArray 类 class StudentArray { private: Student* pStu; // 学生指针 int n; // 学生人数 public: // 构造函数 StudentArray(int n):n(n) { pStu = new Student[n]; // 动态分配 n 个 Student 对象 } // 析构函数 ~StudentArray() { delete[] pStu; // 释放 pStu 所指向的内存 } // 录入 n 个学生信息 void Input() { for (int i = 0; i < n; i++) { cout << "请输入第 " << i+1 << " 个学生的学号、姓名和成绩:" << endl; cin >> pStu[i].num >> pStu[i].name >> pStu[i].score; } } // 输出 n 个学生信息 void Output() { for (int i = 0; i < n; i++) { cout << "第 " << i+1 << " 个学生的学号、姓名和成绩:" << endl; cout << pStu[i].num << " " << pStu[i].name << " " << pStu[i].score << endl; } } // 将 n 个学生信息保存到文件 student.dat 中 void Save() { ofstream outFile("student.dat", ios::binary); // 以二进制的方式打开文件 if (!outFile) { cout << "打开文件失败!" << endl; return; } outFile.write((char*)pStu, n*sizeof(Student)); // 将 pStu 所指向的内存写入文件 outFile.close(); // 关闭文件 } // 按学号查找学生信息 int Find(int num) { // 从文件中读取 n 个学生信息 ifstream inFile("student.dat", ios::binary); if (!inFile) { cout << "打开文件失败!" << endl; return -1; } inFile.read((char*)pStu, n*sizeof(Student)); // 从文件中读取 n 个学生对象 inFile.close(); // 关闭文件 // 从数组中查找学生信息 for (int i = 0; i < n; i++) { if (pStu[i].num == num) { cout << "找到该学生信息:"; cout << pStu[i].num << " " << pStu[i].name << " " << pStu[i].score << endl; return i; // 查找成功,返回学生索引 } } return -1; // 查找失败,返回-1 } };int main() { int n; cout << "请输入学生人数:"; cin >> n; StudentArray stuArr(n); // 定义学生数组对象 stuArr.Input(); // 录入 n 个学生信息 stuArr.Output(); // 输出 n 个学生信息 stuArr.Save(); // 将 n 个学生信息保存到文件 student.dat 中 int num; cout << "请输入要查找的学生学号:"; cin >> num; int index = stuArr.Find(num); // 按学号查找学生信息 if (index == -1) cout << "未找到该学生信息!" << endl; return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值