From e0db23f748c763c366198bbf38ca3ee65081ded2 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sat, 4 May 2024 12:47:51 +0800 Subject: [PATCH] Add file_with_class.cpp --- file_with_class.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 file_with_class.cpp diff --git a/file_with_class.cpp b/file_with_class.cpp new file mode 100644 index 0000000..01909bf --- /dev/null +++ b/file_with_class.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +using std::cin, std::cout, std::string; + +class Student +{ + string name; // 学生姓名 + int course_num; // 学生课程数 + int *score; // 指向动态分配成绩数组 + const char *filename; // 用来处理读写文件的名字 + +public: + Student(string _name, int _course_num, const char *_filename) + : name{_name}, course_num{_course_num}, filename{_filename} + { + score = new int[course_num]{}; + cout << "请依次输入" << course_num << "门课的成绩:"; + for (int i = 0; i < course_num; ++i) + std::cin >> score[i]; + } + + Student(const char *_filename) : filename{_filename} + { + std::ifstream infile(filename, std::ios::in | std::ios::binary); + if (infile) + { + int len{}; + infile.read(reinterpret_cast(&len), sizeof(int)); + char *buffer = new char[len + 1]{}; + infile.read(buffer, len); + name = buffer; + delete[] buffer; + infile.read(reinterpret_cast(&course_num), sizeof(course_num)); + score = new int[course_num]{}; + infile.read(reinterpret_cast(score), course_num * sizeof(int)); + infile.close(); + } + } + ~Student() + { + std::ofstream ofile(filename, std::ios::out | std::ios::binary); + { + int len{static_cast(name.size())}; + ofile.write(reinterpret_cast(&len), sizeof(len)); + ofile.write(name.c_str(), len); + ofile.write(reinterpret_cast(&course_num), sizeof(course_num)); + ofile.write(reinterpret_cast(score), course_num * sizeof(int)); + ofile.close(); + delete[] score; + } + } + friend std::ostream &operator<<(std::ostream &os, Student &s) + { + os << "姓名:" << s.name << " 成绩:"; + for (int i{0}; i < s.course_num; ++i) + os << s.score[i] << '\t'; + return os << '\n'; + } +}; + +int main() +{ + Student s1{"TOM", 5, "s1.dat"}; + // Student s1{"s1.dat"}; 这句话和上面的语句分两次运行即可 + cout << s1; +} \ No newline at end of file