用类写一个图书管理系统包括函数的调用
时间: 2024-03-09 15:50:15 浏览: 64
好的,以下是一个简单的图书管理系统的类实现和函数调用:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 图书类
class Book {
private:
string title;
string author;
string ISBN;
bool is_borrowed;
public:
Book(string title, string author, string ISBN) {
this->title = title;
this->author = author;
this->ISBN = ISBN;
this->is_borrowed = false;
}
void Borrow() {
if (is_borrowed) {
cout << "这本书已经被借走了!" << endl;
return;
}
is_borrowed = true;
cout << "借书成功!" << endl;
}
void Return() {
if (!is_borrowed) {
cout << "这本书没有被借走,无法归还!" << endl;
return;
}
is_borrowed = false;
cout << "还书成功!" << endl;
}
string GetTitle() {
return title;
}
string GetAuthor() {
return author;
}
string GetISBN() {
return ISBN;
}
bool IsBorrowed() {
return is_borrowed;
}
};
// 图书管理系统类
class Library {
private:
vector<Book*> books;
public:
void AddBook(string title, string author, string ISBN) {
Book* book = new Book(title, author, ISBN);
books.push_back(book);
cout << "添加书籍成功!" << endl;
}
void ShowAllBooks() {
for (int i = 0; i < books.size(); i++) {
cout << "书名:" << books[i]->GetTitle() << endl;
cout << "作者:" << books[i]->GetAuthor() << endl;
cout << "ISBN:" << books[i]->GetISBN() << endl;
cout << "是否被借走:" << (books[i]->IsBorrowed() ? "是" : "否") << endl;
cout << endl;
}
}
void BorrowBook(string ISBN) {
for (int i = 0; i < books.size(); i++) {
if (books[i]->GetISBN() == ISBN) {
books[i]->Borrow();
return;
}
}
cout << "没有找到对应的书籍!" << endl;
}
void ReturnBook(string ISBN) {
for (int i = 0; i < books.size(); i++) {
if (books[i]->GetISBN() == ISBN) {
books[i]->Return();
return;
}
}
cout << "没有找到对应的书籍!" << endl;
}
};
// 添加书籍函数
void AddBook(Library& library) {
string title, author, ISBN;
cout << "请输入书名:" << endl;
cin >> title;
cout << "请输入作者:" << endl;
cin >> author;
cout << "请输入ISBN:" << endl;
cin >> ISBN;
library.AddBook(title, author, ISBN);
}
// 显示所有书籍函数
void ShowAllBooks(Library& library) {
library.ShowAllBooks();
}
// 借阅书籍函数
void BorrowBook(Library& library) {
string ISBN;
cout << "请输入要借阅的书籍的ISBN:" << endl;
cin >> ISBN;
library.BorrowBook(ISBN);
}
// 归还书籍函数
void ReturnBook(Library& library) {
string ISBN;
cout << "请输入要归还的书籍的ISBN:" << endl;
cin >> ISBN;
library.ReturnBook(ISBN);
}
// 主函数
int main() {
Library library;
while (true) {
cout << "请输入操作序号:" << endl;
cout << "1:添加书籍" << endl;
cout << "2:显示所有书籍" << endl;
cout << "3:借阅书籍" << endl;
cout << "4:归还书籍" << endl;
cout << "0:退出程序" << endl;
int op;
cin >> op;
if (op == 1) {
AddBook(library);
} else if (op == 2) {
ShowAllBooks(library);
} else if (op == 3) {
BorrowBook(library);
} else if (op == 4) {
ReturnBook(library);
} else if (op == 0) {
break;
} else {
cout << "无效的操作序号,请重新输入!" << endl;
}
}
return 0;
}
```
以上代码实现了一个简单的图书管理系统,包括添加书籍、显示所有书籍、借阅书籍和归还书籍四个功能。主函数通过循环读入用户输入的操作序号,并调用相应的函数来实现功能。每个函数都接受一个 Library 对象的引用作为参数,以便对图书列表进行操作。
阅读全文