用C++写一个图书管理系统代码并解释代码
时间: 2024-01-27 19:06:04 浏览: 22
以下是一个简单的图书管理系统的C++代码,包括添加书籍、删除书籍、查询书籍、显示所有书籍等基本功能。注释已经在代码中标明。
```c++
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Book类表示一本书
class Book {
public:
string name; // 书名
string author; // 作者
int id; // ID号
// 构造函数
Book(string name, string author, int id) {
this->name = name;
this->author = author;
this->id = id;
}
// 显示这本书的信息
void display() {
cout << "ID: " << id << ", Name: " << name << ", Author: " << author << endl;
}
};
// Library类表示整个图书馆
class Library {
public:
vector<Book> books; // 存储所有的书籍
// 添加一本新书
void addBook() {
string name, author;
int id;
cout << "Please enter the book name: ";
cin >> name;
cout << "Please enter the author name: ";
cin >> author;
cout << "Please enter the book ID: ";
cin >> id;
Book newBook(name, author, id);
books.push_back(newBook);
cout << "Book added successfully!" << endl;
}
// 删除一本书
void deleteBook() {
int id;
cout << "Please enter the ID of the book you want to delete: ";
cin >> id;
for (int i = 0; i < books.size(); i++) {
if (books[i].id == id) {
books.erase(books.begin() + i);
cout << "Book deleted successfully!" << endl;
return;
}
}
cout << "Book not found!" << endl;
}
// 查询一本书
void searchBook() {
int id;
cout << "Please enter the ID of the book you want to search: ";
cin >> id;
for (int i = 0; i < books.size(); i++) {
if (books[i].id == id) {
books[i].display();
return;
}
}
cout << "Book not found!" << endl;
}
// 显示所有书籍
void displayAllBooks() {
for (int i = 0; i < books.size(); i++) {
books[i].display();
}
}
};
int main() {
Library library; // 创建一个图书馆对象
while (true) {
// 显示菜单
cout << "\nPlease select an option:" << endl;
cout << "1. Add new book" << endl;
cout << "2. Delete book" << endl;
cout << "3. Search book" << endl;
cout << "4. Display all books" << endl;
cout << "5. Exit" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1:
library.addBook();
break;
case 2:
library.deleteBook();
break;
case 3:
library.searchBook();
break;
case 4:
library.displayAllBooks();
break;
case 5:
exit(0);
default:
cout << "Invalid choice!" << endl;
break;
}
}
return 0;
}
```
这个程序实现了一个简单的图书管理系统,包括添加书籍、删除书籍、查询书籍、显示所有书籍等基本功能。具体实现方法是,定义了一个Book类表示一本书,其中包含书名、作者和ID号等属性,以及一个display()函数用于显示这本书的信息;定义了一个Library类表示整个图书馆,其中包含一个vector<Book>类型的books数组,存储所有的书籍,并且实现了上述的四个基本功能。在main函数中,通过循环显示一个菜单,提示用户选择要进行的操作,然后根据用户的选择调用Library类中相应的函数来实现相应的操作。