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. use c++ Write a main program to test your methods.
时间: 2024-01-11 10:03:22 浏览: 21
Here is the implementation of the Book class with the required methods in C++:
```c++
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
int year;
bool isInLibrary;
public:
Book() {
title = "";
author = "";
year = 0;
isInLibrary = true;
}
void loadData(string title, string author, int year) {
this->title = title;
this->author = author;
this->year = year;
isInLibrary = true;
}
void displayData() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Year of Publication: " << year << endl;
cout << "Is in Library: " << (isInLibrary ? "Yes" : "No") << endl;
}
bool isInTheLibrary() {
return isInLibrary;
}
};
int main() {
Book book;
book.loadData("The Catcher in the Rye", "J.D. Salinger", 1951);
book.displayData();
cout << "Is in the library: " << (book.isInTheLibrary() ? "Yes" : "No") << endl;
return 0;
}
```
The `Book` class has four private member variables: `title`, `author`, `year`, and `isInLibrary`. The `loadData` method takes the values for these variables as parameters and sets them. The `displayData` method prints out the values of these variables. The `isInTheLibrary` method returns the value of `isInLibrary`.
In the `main` function, we create a `Book` object, load it with data, display the data, and check if it is in the library or not.