상세 컨텐츠

본문 제목

[객체지향언어1] 명품 C++ Programming 8장 Open Challenge

C++/문제 풀이

by uzichoi 2025. 7. 4. 15:34

본문

[C++] 명품 C++ Programming 8장 Open Challenge

 

 

<상속 관계의 클래스 작성>

다음과 같은 상속 관계를 가진 Product, Book, CompactDisk, ConversationBook 클래스를 작성하고 아래 실행 화면과 같이 상품을 관리하는 프로그램을 작성하라.
Product 클래스는 상품의 식별자(id), 상품 설명, 생산자, 가격을 나타내는 정보를 포함한다. Book 클래스는 ISBN 번호, 저자, 책 제목 정보를 포함한다. CompactDisc 클래스는 앨범 제목, 가수 이름 정보를 포함한다. ConversationBook은 회화 책에서 다루는 언어 명 정보를 포함한다. 객체 지향 개념에 부합하도록 적절한 접근 지정자, 멤버 변수 및 함수, 생성자 등을 작성하라. main()에서는 최대 100개의 상품을 관리하며, 모든 상품의 정보를 조회할 수 있다. 상품의 식별자는 등록할 때 자동으로 붙인다.

<실행화면>

<소스코드>

#include <string>
#include <iostream>
using namespace std;

class Product {
	int id;	// 식별자
	string description;	// 상품 설명
	string producer;	// 생산자
	string price;	// 가격
public:
	Product() {}
	Product(int id, string discription, string producer, string price) {
		this->id = id; this->description = discription; this->producer = producer; this->price = price;
	}
	void virtual show() = 0;	// 순수 가상 함수
	int getId() { return id; }
	string getDescription() { return description; }
	string getProducer() { return producer; }
	string getPrice() { return price; }
};

class Book : public Product {
	string ISBN, author, title;
public:
	Book(int id, string description, string producer, string price, string title, string author, string ISBN) : Product(id, description, producer, price) {
		this->ISBN = ISBN; this->author = author; this->title = title;
	}
	void show();
	string getISBN() { return ISBN; }
	string getAuthor() { return author; }
	string getTitle() { return title; }
};

void Book::show() {
	cout << "--- 상품 ID : " << getId() << endl;
	cout << "상품설명 : " << getDescription() << endl;
	cout << "가격 :" << getPrice() << endl;
	cout << "ISBN : " << getISBN() << endl;
	cout << "책제목 : " << getTitle() << endl;
	cout << "저자 : " << getAuthor() << endl;
}

class CompactDisk : public Product {
	string title, singer;
public:
	CompactDisk(int id, string description, string producer, string price, string singer, string title) : Product(id, description, producer, price) {
		this->singer = singer; this->title = title;
	}
	void show();
	string getSinger() { return singer; }
	string getTitle() { return title; }
};

void CompactDisk::show() {
	cout << "--- 상품 ID : " << getId() << endl;
	cout << "상품설명 : " << getDescription() << endl;
	cout << "가격 :" << getPrice() << endl;
	cout << "앨범제목 : " << getTitle() << endl;
	cout << "가수 : " << getSinger() << endl;
}

class ConversationBook : public Book {
	string lang;	// 회화 책에서 다루는 언어명
public:
	ConversationBook(int id, string description, string producer, string price, string title, string author, string lang, string ISBN) : Book(id, description, producer, price, title, author, ISBN) {
		this->lang = lang;
	}
	void show();
	string getLang() { return lang; }
};

void ConversationBook::show() {
	cout << "--- 상품 ID : " << getId() << endl;
	cout << "상품설명 : " << getDescription() << endl;
	cout << "가격 :" << getPrice() << endl;
	cout << "ISBN : " << getISBN() << endl;
	cout << "책제목 : " << getTitle() << endl;
	cout << "저자 : " << getAuthor() << endl;
	cout << "언어 : " << getLang() << endl;
}

int main() {
	Product* p[100];
	int id = 0;
	string description, producer, price, ISBN, title, author, singer, lang;

	cout << "***** 상품 관리 프로그램을 작동합니다 *****" << endl;

	while (true) {
		cout << "상품 추가(1), 모든 상품 조회(2), 끝내기(3) ? ";
		int n;
		cin >> n;

		switch (n) {
		case 1:		// 상품 추가
			cout << "상품 종류 책(1), 음악CD(2), 회화책(3) ? ";
			cin >> n;
			cin.ignore();  // '\n' 제거. 생략하면 입력 스트림에 남아 있는 '\n'부터 읽게 되어 무한루프
			if (n == 1) {
				cout << "상품설명>>"; getline(cin, description);
				cout << "생산자>>"; getline(cin, producer);
				cout << "가격>>"; getline(cin, price);
				cout << "책제목>>"; getline(cin, title);
				cout << "저자>>"; getline(cin, author);
				cout << "ISBN>>"; getline(cin, ISBN); 
				cout << endl;
				Book *b = new Book(id, description, producer, price, title, author, ISBN);
				p[id++] = b;
			}
			if (n == 2) {
				cout << "상품설명>>"; getline(cin, description);
				cout << "생산자>>"; getline(cin, producer);
				cout << "가격>>"; getline(cin, price);
				cout << "앨범제목>>"; getline(cin, title);
				cout << "가수>>"; getline(cin, singer); 
				cout << endl;
				CompactDisk* c = new CompactDisk(id, description, producer, price, singer, title);
				p[id++] = c;
			}
			if (n == 3) {
				cout << "상품설명>>"; getline(cin, description);
				cout << "생산자>>"; getline(cin, producer);
				cout << "가격>>"; getline(cin, price);
				cout << "책제목>>"; getline(cin, title);
				cout << "저자>>"; getline(cin, author);
				cout << "언어>>"; getline(cin, lang);
				cout << "ISBN>>"; getline(cin, ISBN);
				cout << endl;
				ConversationBook* cb = new ConversationBook(id, description, producer, price, title, author, lang, ISBN);
				p[id++] = cb;
			}
			break;
		case 2:		// 모든 상품 조회
			for (int i = 0; i < id; i++) {
				p[i]->show();
			}
			break;
		case 3:		// 끝내기
			return 0;
		default:
			cout << "숫자 입력 오류" << endl;
		}
	}

	return 0;
}

 

 

 


1. ostream 멤버 함수

  • ostream& put(char ch)    // 문자 ch를 스트림에 출력
  • ostream& write(char *str, int n)    // str 배열에 있는 n개의 문자를 스트림에 출력
  • ostream& flush()    // 현재 스트림 버퍼에 있는 모든 내용을 강제 출력 

 

 2. istream 멤버 함수와 용도별 구분

  1. 문자 단위
    • int get()
    • istream& get(cahr &ch)
  2. 문자열
    • istream& get(char *s, int n)
  3. 한 줄 읽기
    • istream& get(char *s, int n, char delim='\n')    // 입력 스트림에서 최대 n-1개 문자를 읽어 배열 s에 저장하고 '\0' 문자 삽입. 구분자(디폴트 개행문자)까지 저장
    • istream& getline(char *s, int n, char delim='\n')    // 위와 동일. 그러나 구분자를 스트림 버퍼에서 삭제

 

3. 읽은 문자의 개수 알아내기

  • int gcount()    // 최근 입력 스트림에서 읽은 바이트 수 계산. <Enter> 키 포함 

 

3. 버퍼에서 문자 삭제하기

  • cin.get();    // 빈칸 하나 읽어서 리턴
  • cin.ignore();    // istream& cin.ignore(int n=1, int delim=EOF) 

 

즉, cin.get()은 가장 낮은 수준의 문자 단위 입력 도구이고,
getline()은 문장 단위로 깔끔하게 처리하는 고수준 함수,
cin.ignore()는 버퍼 청소 담당이다. 용도별로 쓰임이 다르니 잘 기억하자!!!

관련글 더보기