帮我用C++写一份较为完整的图书管理系统,能在控制台进行操作,需要基类,派生类,要能进行数据的保存和读取。

时间: 2024-03-04 08:48:20 浏览: 37
好的,以下是一个简单的图书管理系统的代码示例,包括基类和派生类,并支持数据的保存和读取。 ```c++ #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; // 图书基类 class Book { public: Book(string name = "", string author = "", string publisher = "", int year = 0, int price = 0) : m_name(name), m_author(author), m_publisher(publisher), m_year(year), m_price(price) {} virtual ~Book() {} virtual void printInfo() const { cout << "Name: " << m_name << endl; cout << "Author: " << m_author << endl; cout << "Publisher: " << m_publisher << endl; cout << "Year: " << m_year << endl; cout << "Price: " << m_price << endl; } virtual void inputInfo() { cout << "Please input book name: "; cin >> m_name; cout << "Please input author: "; cin >> m_author; cout << "Please input publisher: "; cin >> m_publisher; cout << "Please input year: "; cin >> m_year; cout << "Please input price: "; cin >> m_price; } virtual string toString() const { return m_name + " " + m_author + " " + m_publisher + " " + to_string(m_year) + " " + to_string(m_price); } virtual void fromString(const string& str) { size_t pos = 0; size_t lastPos = 0; string token; vector<string> tokens; while ((pos = str.find(" ", lastPos)) != string::npos) { token = str.substr(lastPos, pos - lastPos); tokens.push_back(token); lastPos = pos + 1; } tokens.push_back(str.substr(lastPos)); if (tokens.size() == 5) { m_name = tokens[0]; m_author = tokens[1]; m_publisher = tokens[2]; m_year = stoi(tokens[3]); m_price = stoi(tokens[4]); } } string getName() const { return m_name; } protected: string m_name; // 书名 string m_author; // 作者 string m_publisher; // 出版社 int m_year; // 出版年份 int m_price; // 价格 }; // 教材派生类 class Textbook : public Book { public: Textbook(string name = "", string author = "", string publisher = "", int year = 0, int price = 0, string subject = "") : Book(name, author, publisher, year, price), m_subject(subject) {} virtual void printInfo() const override { cout << "Textbook: " << endl; Book::printInfo(); cout << "Subject: " << m_subject << endl; } virtual void inputInfo() override { Book::inputInfo(); cout << "Please input subject: "; cin >> m_subject; } virtual string toString() const override { return "Textbook " + Book::toString() + " " + m_subject; } virtual void fromString(const string& str) override { Book::fromString(str); size_t pos = str.find_last_of(" "); if (pos != string::npos && pos + 1 < str.length()) { m_subject = str.substr(pos + 1); } } private: string m_subject; // 学科 }; // 期刊派生类 class Magazine : public Book { public: Magazine(string name = "", string author = "", string publisher = "", int year = 0, int price = 0, int volume = 0) : Book(name, author, publisher, year, price), m_volume(volume) {} virtual void printInfo() const override { cout << "Magazine: " << endl; Book::printInfo(); cout << "Volume: " << m_volume << endl; } virtual void inputInfo() override { Book::inputInfo(); cout << "Please input volume: "; cin >> m_volume; } virtual string toString() const override { return "Magazine " + Book::toString() + " " + to_string(m_volume); } virtual void fromString(const string& str) override { Book::fromString(str); size_t pos = str.find_last_of(" "); if (pos != string::npos && pos + 1 < str.length()) { m_volume = stoi(str.substr(pos + 1)); } } private: int m_volume; // 卷数 }; // 图书管理类 class BookManager { public: BookManager() {} virtual ~BookManager() {} void addBook(Book* book) { m_books.push_back(book); } void removeBook(const string& name) { for (vector<Book*>::iterator it = m_books.begin(); it != m_books.end(); ++it) { if ((*it)->getName() == name) { delete *it; m_books.erase(it); break; } } } void displayAllBooks() const { cout << "All Books:" << endl; for (const Book* book : m_books) { book->printInfo(); cout << endl; } } void saveToFile(const string& filename) { ofstream outFile(filename); if (outFile.is_open()) { for (const Book* book : m_books) { outFile << book->toString() << endl; } outFile.close(); cout << "Save to file " << filename << " successfully." << endl; } else { cout << "Failed to save to file " << filename << "." << endl; } } void loadFromFile(const string& filename) { ifstream inFile(filename); if (inFile.is_open()) { string line; while (getline(inFile, line)) { size_t pos = line.find(" "); if (pos != string::npos) { string type = line.substr(0, pos); if (type == "Textbook") { Textbook* book = new Textbook; book->fromString(line); m_books.push_back(book); } else if (type == "Magazine") { Magazine* book = new Magazine; book->fromString(line); m_books.push_back(book); } } } inFile.close(); cout << "Load from file " << filename << " successfully." << endl; } else { cout << "Failed to load from file " << filename << "." << endl; } } private: vector<Book*> m_books; // 图书列表 }; // 主函数 int main() { BookManager manager; // 加载数据 manager.loadFromFile("books.txt"); // 进入主循环 while (true) { cout << "Please select an action:" << endl; cout << "1. Add book" << endl; cout << "2. Remove book" << endl; cout << "3. Display all books" << endl; cout << "4. Save to file" << endl; cout << "5. Load from file" << endl; cout << "6. Exit" << endl; int choice = 0; cout << "Your choice: "; cin >> choice; switch (choice) { case 1: { cout << "Please select a book type:" << endl; cout << "1. Textbook" << endl; cout << "2. Magazine" << endl; int typeChoice = 0; cout << "Your choice: "; cin >> typeChoice; if (typeChoice == 1) { Textbook* book = new Textbook; book->inputInfo(); manager.addBook(book); } else if (typeChoice == 2) { Magazine* book = new Magazine; book->inputInfo(); manager.addBook(book); } else { cout << "Invalid choice." << endl; } break; } case 2: { string name; cout << "Please input book name: "; cin >> name; manager.removeBook(name); break; } case 3: { manager.displayAllBooks(); break; } case 4: { string filename; cout << "Please input file name: "; cin >> filename; manager.saveToFile(filename); break; } case 5: { string filename; cout << "Please input file name: "; cin >> filename; manager.loadFromFile(filename); break; } case 6: { // 退出程序,保存数据 manager.saveToFile("books.txt"); return 0; } default: { cout << "Invalid choice." << endl; break; } } } return 0; } ``` 在这个示例中,我们定义了一个 `Book` 基类,并派生出 `Textbook` 和 `Magazine` 两个子类,分别表示教材和期刊。我们使用 `vector` 存储所有的图书,并提供了一些基本的操作,例如添加图书、删除图书、显示所有图书、保存数据到文件和从文件加载数据等。 在 `Book` 基类中,我们定义了一些基本的属性和方法,例如书名、作者、出版社、出版年份、价格等,以及打印、输入、转为字符串和从字符串中读取等方法。在 `Textbook` 和 `Magazine` 子类中,我们通过继承和重载实现了一些特殊的属性和方法,例如学科和卷数等。 在主函数中,我们通过一个简单的循环来处理用户的选择,例如添加图书、删除图书、显示所有图书、保存数据到文件和从文件加载数据等。在每个操作中,我们都通过调用 `BookManager` 类的方法来完成相应的操作。 这个示例只是一个简单的图书管理系统,你可以根据自己的需求进行修改和扩展。如果你对 C++ 的面向对象编程有一定的了解,应该可以很容易地理解这个示例,如果有任何问题或建议,欢迎与我交流。

相关推荐

最新推荐

recommend-type

基于Python的蓝桥杯竞赛平台的设计与实现

【作品名称】:基于Python的蓝桥杯竞赛平台的设计与实现 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【项目介绍】:基于Python的蓝桥杯竞赛平台的设计与实现
recommend-type

python实现基于深度学习TensorFlow框架的花朵识别项目源码.zip

python实现基于深度学习TensorFlow框架的花朵识别项目源码.zip
recommend-type

3-9.py

3-9
recommend-type

郊狼优化算法COA MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用

郊狼优化算法COA MATLAB源码, 应用案例为函数极值求解以及优化svm进行分类,代码注释详细,可结合自身需求进行应用
recommend-type

563563565+3859

5635356
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。