icon안동민 개발노트

간단한 클래스 설계 및 구현


요구사항 분석

 Book 클래스는 다음 요구사항을 만족해야 합니다.

  1. 책의 제목, 저자, ISBN, 출판년도, 대출 가능 여부를 저장할 수 있어야 합니다.
  2. 책 정보를 설정하고 조회할 수 있어야 합니다.
  3. 책을 대출하고 반납하는 기능이 있어야 합니다.
  4. 책 정보를 문자열 형태로 반환할 수 있어야 합니다.
  5. 두 책의 정보를 비교할 수 있어야 합니다. (ISBN 기준)

클래스 설계

 먼저 Book 클래스의 기본 구조를 설계해봅시다.

#include <string>
 
class Book {
private:
    std::string title;
    std::string author;
    std::string ISBN;
    int publicationYear;
    bool isAvailable;
 
public:
    // 생성자
    Book(const std::string& title, const std::string& author, 
         const std::string& ISBN, int year);
 
    // 접근자 및 설정자 메서드
    std::string getTitle() const;
    void setTitle(const std::string& title);
    std::string getAuthor() const;
    void setAuthor(const std::string& author);
    std::string getISBN() const;
    void setISBN(const std::string& ISBN);
    int getPublicationYear() const;
    void setPublicationYear(int year);
    bool isBookAvailable() const;
 
    // 기타 메서드
    void borrowBook();
    void returnBook();
    std::string toString() const;
    bool operator==(const Book& other) const;
};

클래스 구현

 이제 Book 클래스의 멤버 함수들을 구현해봅시다.

#include <sstream>
 
// 생성자
Book::Book(const std::string& title, const std::string& author, 
           const std::string& ISBN, int year)
    : title(title), author(author), ISBN(ISBN), 
      publicationYear(year), isAvailable(true) {}
 
// 접근자 및 설정자 메서드
std::string Book::getTitle() const { return title; }
void Book::setTitle(const std::string& title) { this->title = title; }
std::string Book::getAuthor() const { return author; }
void Book::setAuthor(const std::string& author) { this->author = author; }
std::string Book::getISBN() const { return ISBN; }
void Book::setISBN(const std::string& ISBN) { this->ISBN = ISBN; }
int Book::getPublicationYear() const { return publicationYear; }
void Book::setPublicationYear(int year) { publicationYear = year; }
bool Book::isBookAvailable() const { return isAvailable; }
 
// 대출 및 반납 메서드
void Book::borrowBook() {
    if (isAvailable) {
        isAvailable = false;
    } else {
        throw std::runtime_error("Book is not available for borrowing");
    }
}
 
void Book::returnBook() {
    if (!isAvailable) {
        isAvailable = true;
    } else {
        throw std::runtime_error("Book is already in the library");
    }
}
 
// 책 정보를 문자열로 반환
std::string Book::toString() const {
    std::ostringstream oss;
    oss << "Title: " << title << ", Author: " << author 
        << ", ISBN: " << ISBN << ", Year: " << publicationYear 
        << ", Available: " << (isAvailable ? "Yes" : "No");
    return oss.str();
}
 
// 두 책의 정보 비교 (ISBN 기준)
bool Book::operator==(const Book& other) const {
    return ISBN == other.ISBN;
}

클래스 사용 예제

 이제 Book 클래스를 사용하는 간단한 예제를 작성해봅시다.

#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
    // 책 객체 생성
    Book book1("The C++ Programming Language", "Bjarne Stroustrup", "978-0321563842", 2013);
    Book book2("Effective Modern C++", "Scott Meyers", "978-1491903996", 2014);
    Book book3("C++ Primer", "Stanley B. Lippman", "978-0321714114", 2012);
 
    // 벡터에 책 추가
    std::vector<Book> library = {book1, book2, book3};
 
    // 책 정보 출력
    for (const auto& book : library) {
        std::cout << book.toString() << std::endl;
    }
 
    // 책 대출
    try {
        library[0].borrowBook();
        std::cout << "\nAfter borrowing " << library[0].getTitle() << ":" << std::endl;
        std::cout << library[0].toString() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }
 
    // 특정 ISBN을 가진 책 찾기
    std::string searchISBN = "978-1491903996";
    auto it = std::find_if(library.begin(), library.end(),
                           [&searchISBN](const Book& b) { return b.getISBN() == searchISBN; });
    if (it != library.end()) {
        std::cout << "\nFound book: " << it->toString() << std::endl;
    } else {
        std::cout << "\nBook with ISBN " << searchISBN << " not found." << std::endl;
    }
 
    return 0;
}

실행 결과

Title: The C++ Programming Language, Author: Bjarne Stroustrup, ISBN: 978-0321563842, Year: 2013, Available: Yes
Title: Effective Modern C++, Author: Scott Meyers, ISBN: 978-1491903996, Year: 2014, Available: Yes
Title: C++ Primer, Author: Stanley B. Lippman, ISBN: 978-0321714114, Year: 2012, Available: Yes
 
After borrowing The C++ Programming Language:
Title: The C++ Programming Language, Author: Bjarne Stroustrup, ISBN: 978-0321563842, Year: 2013, Available: No
 
Found book: Title: Effective Modern C++, Author: Scott Meyers, ISBN: 978-1491903996, Year: 2014, Available: Yes

실습

  1. Book 클래스에 책의 페이지 수와 장르를 추가하고, 이를 활용하는 메서드를 구현해보세요.
  2. 도서관의 여러 책을 관리하는 Library 클래스를 설계하고 구현해보세요.
  3. 파일 입출력을 활용하여 책 정보를 파일에 저장하고 불러오는 기능을 추가해보세요.


참고 자료

  • Stroustrup, Bjarne. "The C++ Programming Language (4th Edition)"
  • Meyers, Scott. "Effective Modern C++ : 42 Specific Ways to Improve Your Use of C++ 11 and C++ 14"
  • Sutter, Herb and Alexandrescu, Andrei. "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices"
  • C++ Reference : Classes
  • ISO C++ Core Guidelines : C : Classes and Class Hierarchies