帮我用c++写一个图书管理系统的代码
时间: 2023-08-28 15:26:33 浏览: 62
好的,这是一个简单的图书管理系统的C++代码示例:
```
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Book {
private:
string title;
string author;
int id;
public:
Book(string title, string author, int id) {
this->title = title;
this->author = author;
this->id = id;
}
string getTitle() {
return title;
}
string getAuthor() {
return author;
}
int getId() {
return id;
}
};
class Library {
private:
vector<Book> books;
public:
void addBook(Book book) {
books.push_back(book);
}
void removeBook(int id) {
for (int i = 0; i < books.size(); i++) {
if (books[i].getId() == id) {
books.erase(books.begin() + i);
break;
}
}
}
void printBooks() {
for (int i = 0; i < books.size(); i++) {
cout << "Title: " << books[i].getTitle() << endl;
cout << "Author: " << books[i].getAuthor() << endl;
cout << "ID: " << books[i].getId() << endl;
cout << "----------------------" << endl;
}
}
};
int main() {
Library library;
library.addBook(Book("The Great Gatsby", "F. Scott Fitzgerald", 1));
library.addBook(Book("To Kill a Mockingbird", "Harper Lee", 2));
library.addBook(Book("1984", "George Orwell", 3));
library.printBooks();
library.removeBook(2);
library.printBooks();
return 0;
}
```
这个代码实现了一个简单的图书管理系统,包括添加书籍、删除书籍和打印书籍列表的功能。其中`Book`类表示一本书,包含书名、作者和ID等信息,`Library`类表示整个图书馆,包含了一个`vector`向量来存储所有的书籍。在主函数中,我们首先创建一个`Library`对象,然后添加三本书,打印书籍列表,然后删除第二本书并再次打印书籍列表。
阅读全文