多文件编程的图书管理系统
时间: 2023-12-27 21:25:19 浏览: 36
多文件编程的图书管理系统可以通过将不同功能的代码分别写在不同的文件中来实现模块化和代码复用。下面是一个简单的示例:
1. 创建一个名为`book.h`的头文件,用于定义图书类和相关函数:
```cpp
#ifndef BOOK_H
#define BOOK_H
#include <string>
class Book {
private:
std::string title;
std::string author;
int year;
public:
Book(std::string title, std::string author, int year);
std::string getTitle();
std::string getAuthor();
int getYear();
};
#endif
```
2. 创建一个名为`book.cpp`的源文件,实现图书类的成员函数:
```cpp
#include "book.h"
Book::Book(std::string title, std::string author, int year) {
this->title = title;
this->author = author;
this->year = year;
}
std::string Book::getTitle() {
return title;
}
std::string Book::getAuthor() {
return author;
}
int Book::getYear() {
return year;
}
```
3. 创建一个名为`library.h`的头文件,用于定义图书馆类和相关函数:
```cpp
#ifndef LIBRARY_H
#define LIBRARY_H
#include <vector>
#include "book.h"
class Library {
private:
std::vector<Book> books;
public:
void addBook(Book book);
void removeBook(std::string title);
void displayBooks();
};
#endif
```
4. 创建一个名为`library.cpp`的源文件,实现图书馆类的成员函数:
```cpp
#include "library.h"
#include <iostream>
void Library::addBook(Book book) {
books.push_back(book);
}
void Library::removeBook(std::string title) {
for (auto it = books.begin(); it != books.end(); ++it) {
if (it->getTitle() == title) {
books.erase(it);
break;
}
}
}
void Library::displayBooks() {
for (const auto& book : books) {
std::cout << "Title: " << book.getTitle() << ", Author: " << book.getAuthor() << ", Year: " << book.getYear() << std::endl;
}
}
```
5. 创建一个名为`main.cpp`的源文件,用于实现图书管理系统的交互界面:
```cpp
#include <iostream>
#include "book.h"
#include "library.h"
int main() {
Library library;
// 添加图书
Book book1("Book 1", "Author 1", 2021);
Book book2("Book 2", "Author 2", 2022);
library.addBook(book1);
library.addBook(book2);
// 显示图书
library.displayBooks();
// 删除图书
library.removeBook("Book 1");
// 再次显示图书
library.displayBooks();
return 0;
}
```
编译并运行以上代码,你将看到图书管理系统的交互界面,可以添加、删除和显示图书信息。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)