تمرين فصيلة الكتاب
قم بإنشاء فصيلة تمتل كتابا في مكتبة .قم بتعريف الخصائص الأساسية للكتاب متل العنوان والمؤلف وسنة النشر .قم بتنفيذ وظائف لإضافة كتاب إلى المكتبه والبحت عن كتب بالعنوان أو المؤلف وعرض تفاصيل الكتب
C++
Assistant
بالطبع! سأقوم بإنشاء فصيلة (Class) تمثل كتابًا في مكتبة باستخدام لغة C++. الفصيلة ستحتوي على الخصائص الأساسية مثل العنوان، المؤلف، وسنة النشر. سأقوم أيضًا بتعريف وظائف لإضافة كتاب إلى المكتبة، البحث عن كتب حسب العنوان أو المؤلف، وعرض تفاصيل الكتب.
إليك الكود:
cpp
#include <iostream>
#include <vector>
#include <string>
class Book {
private:
std::string title;
std::string author;
int year;
public:
Book(std::string t, std::string a, int y) : title(t), author(a), year(y) {}
std::string getTitle() const {
return title;
}
std::string getAuthor() const {
return author;
}
int getYear() const {
return year;
}
void displayInfo() const {
std::cout << "Title: " << title << ", Author: " << author << ", Year: " << year << std::endl;
}
};
class Library {
private:
std::vector<Book> books;
public:
void addBook(const Book& book) {
books.push_back(book);
}
void searchByTitle(const std::string& title) const {
bool found = false;
for (const auto& book : books) {
if (book.getTitle() == title) {
book.displayInfo();
found = true;
}
}
if (!found) {
std::cout << "No book found with the title: " << title << std::endl;
}
}
void searchByAuthor(const std::string& author) const {
bool found = false;
for (const auto& book : books) {
if (book.getAuthor() == author) {
book.displayInfo();
found = true;
}
}
if (!found) {
std::cout << "No books found by the author: " << author << std::endl;
}
}
void displayAllBooks() const {
if (books.empty()) {
std::cout << "No books in the library." << std::endl;
return;
}
for (const auto& book : books) {
book.displayInfo();
}
}
};
int main() {
Library library;
// Adding books to the library
library.addBook(Book("The Catcher in the Rye", "J.D. Salinger", 1951));
library.addBook(Book("To Kill a Mockingbird", "Harper Lee", 1960));
library.addBook(Book("1984", "George Orwell", 1949));
// Display all books
std::cout << "All books in the library:\n";
library.displayAllBooks();
// Search for a book by title
std::cout << "\nSearching for books with title '1984':\n";
library.searchByTitle("1984");
// Search for books by author
std::cout << "\nSearching for books by author 'Harper Lee':\n";
library.searchByAuthor("Harper Lee");
return 0;
}
شرح الكود:
فصيلة Book: تمثل كتابًا، تحتوي على الخصائص الثلاث (العنوان، المؤلف، وسنة النشر) وبعض الوظائف للحصول على المعلومات وعرض تفاصيل الكتاب.
فصيلة Library: تمثل مكتبة تحتوي على مجموعة من الكتب، مع وظيفتين للبحث عن الكتب حسب العنوان أو المؤلف، ووظيفة لعرض جميع الكتب في المكتبة.
البرنامج الرئيسي (main): يقوم بإنشاء مكتبة وإضافة بعض الكتب إليها، ثم يعرض جميع الكتب ويبحث عن كتب معينة حسب العنوان أو المؤلف.
يمكنك نسخ هذا الكود ولصقه في بيئة تطوير C++ لتجربته.