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-10 12:05:07 浏览: 68
Sure, here's an example implementation in C++:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Book {
public:
string title;
string author;
int year;
bool in_library;
void load_data() {
cout << "Enter book title: ";
getline(cin, title);
cout << "Enter book author: ";
getline(cin, author);
cout << "Enter year of publication: ";
cin >> year;
cout << "Is the book in the library? (1 for yes, 0 for no): ";
cin >> in_library;
}
void display_data() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Year of publication: " << year << endl;
if (in_library) {
cout << "Status: available" << endl;
} else {
cout << "Status: taken out" << endl;
}
}
bool is_in_library() {
return in_library;
}
};
int main() {
Book book;
book.load_data();
book.display_data();
cout << "Is the book in the library? " << book.is_in_library() << endl;
return 0;
}
```
In this implementation, the `Book` class has four member variables: `title`, `author`, `year`, and `in_library`. The `load_data` method prompts the user to enter information for each of these variables. The `display_data` method outputs the book's information to the console. The `is_in_library` method returns the `in_library` variable. Finally, the `main` function creates a `Book` object, calls its `load_data` method to populate its member variables, calls its `display_data` method to output its information, and calls its `is_in_library` method to check if it's in the library.
阅读全文