用C++写一个图书管理系统
时间: 2023-10-03 17:08:14 浏览: 134
好的,这是一个简单的图书管理系统的 C++ 代码,供你参考:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 定义 Book 类
class Book {
public:
Book(string id, string name, string author, string press, int year): _id(id), _name(name), _author(author), _press(press), _year(year){}
string get_id() { return _id; }
string get_name() { return _name; }
string get_author() { return _author; }
string get_press() { return _press; }
int get_year() { return _year; }
void display() { cout << _id << "\t" << _name << "\t" << _author << "\t" << _press << "\t" << _year << endl; }
private:
string _id; // 书籍编号
string _name; // 书籍名称
string _author; // 书籍作者
string _press; // 出版社
int _year; // 出版年份
};
// 定义 Library 类
class Library {
public:
void add_book(Book book) { _books.push_back(book); } // 添加书籍
void remove_book(string id); // 删除书籍
void display_all_books(); // 显示所有书籍
void search_book_by_id(string id); // 根据编号查找书籍
void search_book_by_name(string name); // 根据名称查找书籍
private:
vector<Book> _books;
};
// 删除指定编号的书籍
void Library::remove_book(string id) {
for (vector<Book>::iterator it = _books.begin(); it != _books.end(); ++it) {
if (it->get_id() == id) {
_books.erase(it);
break;
}
}
}
// 显示所有书籍
void Library::display_all_books() {
cout << "ID\tName\tAuthor\tPress\tYear" << endl;
for (vector<Book>::iterator it = _books.begin(); it != _books.end(); ++it) {
it->display();
}
}
// 根据编号查找书籍
void Library::search_book_by_id(string id) {
cout << "ID\tName\tAuthor\tPress\tYear" << endl;
for (vector<Book>::iterator it = _books.begin(); it != _books.end(); ++it) {
if (it->get_id() == id) {
it->display();
break;
}
}
}
// 根据名称查找书籍
void Library::search_book_by_name(string name) {
cout << "ID\tName\tAuthor\tPress\tYear" << endl;
for (vector<Book>::iterator it = _books.begin(); it != _books.end(); ++it) {
if (it->get_name() == name) {
it->display();
}
}
}
// 测试
int main() {
Library library;
Book book1("001", "C++ Programming", "Bjarne Stroustrup", "Addison-Wesley", 2013);
Book book2("002", "Thinking in Java", "Bruce Eckel", "Prentice Hall", 2006);
library.add_book(book1);
library.add_book(book2);
library.display_all_books();
cout << endl;
library.remove_book("001");
library.search_book_by_id("002");
cout << endl;
library.search_book_by_name("C++ Programming");
return 0;
}
```
这个程序通过定义 Book 类和 Library 类来实现图书管理系统的功能。其中 Book 类包含书籍的编号、名称、作者、出版社和出版年份等信息,Library 类包含了添加、删除、查找书籍等功能。在 main 函数中,我们添加了两本书籍,然后显示所有书籍,再删除一本书籍,根据编号查找一本书籍,最后根据名称查找书籍。
阅读全文