The library requires a class to store information about a book. Set up a class to hold data including title, author, year of publication, and a boolean variable to indicate if the book is in the library or if the book has been taken out. Create a method to load the data for one book. Create another method to display the data for a book. Create another method to check if a book is in the library or not. Write a main program to test your methods. 用c++
时间: 2023-12-30 14:07:01 浏览: 106
图书管理. c++
以下是一个可能的类定义,包括所需的数据成员和方法:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
int year;
bool in_library;
public:
void load_data(string t, string a, int y, bool l) {
title = t;
author = a;
year = y;
in_library = l;
}
void display_data() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Year of publication: " << year << endl;
if (in_library) {
cout << "In library: Yes" << endl;
} else {
cout << "In library: No" << endl;
}
}
bool is_in_library() {
return in_library;
}
};
int main() {
Book b1;
b1.load_data("The Catcher in the Rye", "J.D. Salinger", 1951, true);
b1.display_data();
if (b1.is_in_library()) {
cout << "This book is in the library." << endl;
} else {
cout << "This book has been taken out." << endl;
}
return 0;
}
```
这个程序演示了如何创建一个 `Book` 类的实例,使用 `load_data` 方法为其加载数据,使用 `display_data` 方法显示数据,并使用 `is_in_library` 方法检查书籍是否在库中。在这个例子中,`Book` 类只有一个实例,但在实际情况下,可以创建多个不同的 `Book` 对象,每个对象表示不同的书籍。
阅读全文