|
|
Chapter 03
: 클래스와 객체
실습 문제 1번
: main()의 실행 결과가 다음과 같도록 Tower 클래스를 작성하라.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | // main.cpp #include "test1.h" int main() { MINSEO::Tower myTower; MINSEO::Tower seoulTower(100); cout << "높이는 " << myTower.getHeiht() << "미터" << endl; cout << "높이는 " << seoulTower.getHeiht() << "미터" << endl; return 0; } // test1.cpp #include "test1.h" namespace MINSEO { Tower::Tower() { height = 1; } Tower::Tower(int height) { this->height = height; } int Tower::getHeiht() { return height; } } // test1.h #pragma once #ifndef TEST_1 #define TEST_1 #include <iostream> using namespace std; namespace MINSEO { class Tower { int height; public: Tower(); Tower(int height); int getHeiht(); }; } #endif // !TEST_1 | cs |
실습 문제 2번
: 날짜를 다루는 Date 클래스를 작성하고자 한다. 클래스 Date를 작성하여 프로그램에 추가하라.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | // main.cpp #include "test2.h" int main() { MINSEO::Date birth(2014, 3, 20); MINSEO::Date independenceDay("1945/8/15"); independenceDay.show(); cout << birth.getYear() << "," << birth.getMonth() << ',' << birth.getDay() << endl; return 0; } // test2.cpp #include "test2.h" namespace MINSEO { Date::Date(int year, int month, int day) { this->year = year; this->month = month; this->day = day; } Date::Date(string date) { int next; this->year = stoi(date); next = date.find('/'); this->month = stoi(date.substr(next + 1)); next = date.find('/', next + 1); this->day = stoi(date.substr(next + 1)); } void Date::show() { cout << year << "년" << month << "월" << day << "일" << endl; } int Date::getYear() { return year; } int Date::getMonth() { return month; } int Date::getDay() { return day; } } // test2.h #pragma once #ifndef TEST_2 #define TEST_2 #include <iostream> #include <string> using namespace std; namespace MINSEO { class Date { int year, month, day; public: Date(int year, int month, int day); Date(string date); void show(); int getYear(); int getMonth(); int getDay(); }; } #endif // !TEST_2 | cs |
실습 문제 3번
: 은행에서 사용하는 프로그램 작성하라.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | // main.cpp #include "test3.h" int main() { MINSEO::Account a("Kitea", 1, 5000); a.deposit(50000); cout << a.getOwner() << "의 잔액은 " << a.inquiry() << endl; int money = a.withdraw(20000); cout << a.getOwner() << "의 잔액은 " << a.inquiry() << endl; return 0; } // test2.cpp #include "test3.h" namespace MINSEO { Account::Account(string name, int id, int balance) { this->name = name; this->id = id; this->balance = balance; } void Account::deposit(int money) { balance += money; } string Account::getOwner() { return name; } int Account::inquiry() { return balance; } int Account::withdraw(int money) { balance -= money; return balance; } } // test2.h #pragma once #ifndef TEST_3 #define TEST_3 #include <iostream> #include <string> using namespace std; namespace MINSEO { class Account { string name; int id, balance; public: Account(string name, int id, int balance); void deposit(int money); string getOwner(); int inquiry(); int withdraw(int money); }; } #endif // !TEST_3 | cs |
실습 문제 4번
: CoffeeMachine 클래스를 만들어보자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | // main.cpp #include "test4.h" int main() { MINSEO::CoffeeMachine java(5, 10, 3); java.drinkEspresso(); java.show(); java.drinkAmericano(); java.show(); java.drinkSugarCoffee(); java.show(); java.fill(); java.show(); return 0; } // test2.cpp #include "test4.h" namespace MINSEO { CoffeeMachine::CoffeeMachine(int coffee, int water, int sugar) { this->coffee = coffee; this->water = water; this->sugar = sugar; } void CoffeeMachine::drinkEspresso() { coffee--; water--; } void CoffeeMachine::drinkAmericano() { drinkEspresso(); water--; } void CoffeeMachine::drinkSugarCoffee() { drinkAmericano(); sugar--; } void CoffeeMachine::fill() { coffee = water = sugar = 10; } void CoffeeMachine::show() { cout << "커피 머신 상태, 커피:" << coffee << "\t물:" << water << "\t설탕:" << sugar << endl; } } // test2.h #pragma once #ifndef TEST_4 #define TEST_4 #include <iostream> using namespace std; namespace MINSEO { class CoffeeMachine { int coffee, water, sugar; public: CoffeeMachine(int coffee, int water, int sugar); void drinkEspresso(); void drinkAmericano(); void drinkSugarCoffee(); void fill(); void show(); }; } #endif // !TEST_4 | cs |
실습 문제 5번
: 랜덤 수 발생시키는 Random 클래스를 만들자.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | // main.cpp #include "test5.h" int main() { srand(time(NULL)); MINSEO::Random r; cout << "-- 0에서 " << RAND_MAX << "까지의 랜덤 정수 10개 -- " << endl; for (int i = 0; i < 10; i++) { int n = r.next(); cout << n << ' '; } cout << endl << endl << "-- 2에서 4까지의 랜덤 정수 10개 --" << endl; for (int i = 0; i < 10; i++) { int n = r.nextInrange(2, 4); cout << n << ' '; } cout << endl; return 0; } // test2.cpp #include "test5.h" namespace MINSEO { Random::Random() { r = 0; } int Random::next() { return r = rand() % RAND_MAX; } int Random::nextInrange(int num1, int num2) { return r = (rand() % num1 - 1) + num2; } } // test2.h #pragma once #ifndef TEST_5 #define TEST_5 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; namespace MINSEO { class Random { int r; public: Random(); int next(); int nextInrange(int num1, int num2); }; } #endif // !TEST_5 | cs |
실습 문제 6번
: 짝수 정수만 랜덤하게 발생시키는 EvenRandom 클래스
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | // main.cpp #include "test6.h" int main() { srand(time(NULL)); MINSEO::EvenRandom r; cout << "-- 0에서 " << RAND_MAX << "까지의 짝수 10개 -- " << endl; for (int i = 0; i < 10; i++) { int n = r.next(); cout << n << ' '; } cout << endl << endl << "-- 2에서 4까지의 짝수 10개 --" << endl; for (int i = 0; i < 10; i++) { int n = r.nextInrange(2, 4); cout << n << ' '; } cout << endl; return 0; } // test6.cpp #include "test6.h" namespace MINSEO { EvenRandom::EvenRandom() { r = 0; } int EvenRandom::next() { return r = (rand() % (RAND_MAX / 2)) * 2; } int EvenRandom::nextInrange(int num1, int num2) { int start = (num1 + 1) / 2; int end = num2 / 2; return r = (rand() % (end - start + 1) * 2) + num1; } } // test6.h #pragma once #ifndef TEST_6 #define TEST_6 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; namespace MINSEO { class EvenRandom { int r; public: EvenRandom(); int next(); int nextInrange(int num1, int num2); }; } #endif // !TEST_6 | cs |
실습 문제 7번
: 짝수 홀수 선택할 수 있도록 SelectRandom 클래스 작성하고 짝수 10개, 홀수 10개 랜덤 발생시키는 프로그램 작성
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | // main.cpp #include "test7.h" int main() { srand(time(NULL)); MINSEO::SelectRandom sr; cout << "짝수 10개: "; for (int i = 0; i < 10; ++i) { cout << sr.nextEven() << " "; } cout << endl; cout << "홀수 10개: "; for (int i = 0; i < 10; ++i) { cout << sr.nextOdd() << " "; } cout << endl; return 0; } // test7.cpp #include "test7.h" namespace MINSEO { SelectRandom::SelectRandom() { srand(time(NULL)); r = 0; } int SelectRandom::nextEven() { return r = (rand() % (RAND_MAX / 2)) * 2; } int SelectRandom::nextOdd() { return r = (rand() % (RAND_MAX / 2)) * 2 + 1; } } // test7.h #pragma once #ifndef TEST_7 #define TEST_7 #include <iostream> #include <cstdlib> #include <ctime> using namespace std; namespace MINSEO { class SelectRandom { int r; public: SelectRandom(); int nextEven(); int nextOdd(); }; } #endif // !TEST_7 | cs |
실습 문제 8번
: int 타입의 정수를 객체화한 Integer 클래스를 작성하라.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | // main.cpp #include "test8.h" int main() { MINSEO::Integer n(30); cout << n.get() << ' '; n.set(50); cout << n.get() << ' '; MINSEO::Integer m("300"); cout << m.get() << ' '; cout << m.isEven(); return 0; } // test8.cpp #include "test8.h" namespace MINSEO { Integer::Integer(int n) { this->n = n; } Integer::Integer(string str) { this->n = stoi(str); } void Integer::set(int n) { this->n = n; } int Integer::get() { return n; } bool Integer::isEven() { if (n % 2 == 0) { return true; } else { return false; } } } // test8.h #pragma once #ifndef TEST_8 #define TEST_8 #include <iostream> #include <string> using namespace std; namespace MINSEO { class Integer { int n; public: Integer(int n); Integer(string str); void set(int n); int get(); bool isEven(); }; } #endif // !TEST_8 | cs |
실습 문제 9번
: Oval 클래스는 주어진 사각형에 내접하는 타원을 추상화하는 클래스.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | // main.cpp #include "test9.h" int main() { MINSEO::Oval a, b(3, 4); a.set(10, 20); a.show(); cout << b.getWidth() << ", " << b.getHeight() << endl; return 0; } // test9.cpp #include "test9.h" namespace MINSEO { Oval::Oval() { width = height = 1; } Oval::Oval(int width, int height) { this->width = width; this->height = height; } Oval::~Oval() { cout << "Oval 소멸 : width = " << width << ", height = " << height << endl; } int Oval::getWidth() { return width; } int Oval::getHeight() { return height; } void Oval::set(int width, int height) { this->width = width; this->height = height; } void Oval::show() { cout << "width = " << width << ", height = " << height << endl; } } // test9.h #pragma once #ifndef TEST_9 #define TEST_9 #include <iostream> using namespace std; namespace MINSEO { class Oval { int width, height; public: Oval(); Oval(int width, int height); ~Oval(); int getWidth(); int getHeight(); void set(int width, int height); void show(); }; } #endif // !TEST_9 | cs |
실습 문제 10번
: 연산을 수행하는 클래스를 각각 만들기.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | // main.cpp #include "test10.h" int main() { MINSEO::Add a; MINSEO::Sub s; MINSEO::Mul m; MINSEO::Div d; while (true) { cout << "두 정수와 연산자를 입력하세요 >> "; int x, y; char op; cin >> x >> y >> op; switch (op) { case '+': a.setValue(x, y); cout << a.calculate() << endl; break; case '-': s.setValue(x, y); cout << s.calculate() << endl; break; case '*': m.setValue(x, y); cout << m.calculate() << endl; break; case '/': d.setValue(x, y); cout << d.calculate() << endl; break; default: break; } } return 0; } // test10.cpp #include "test10.h" namespace MINSEO { void Sub::setValue(int x, int y) { a = x; b = y; } int Sub::calculate() { return a - b; } void Mul::setValue(int x, int y) { a = x; b = y; } int Mul::calculate() { return a * b; } void Add::setValue(int x, int y) { a = x; b = y; } int Add::calculate() { return a + b; } void Div::setValue(int x, int y) { a = x; b = y; } int Div::calculate() { return a / b; } } // test10.h #pragma once #ifndef TEST_10 #define TEST_10 #include <iostream> using namespace std; namespace MINSEO { class Add { int a, b; public: void setValue(int x, int y); int calculate(); }; class Sub { int a, b; public: void setValue(int x, int y); int calculate(); }; class Mul { int a, b; public: void setValue(int x, int y); int calculate(); }; class Div { int a, b; public: void setValue(int x, int y); int calculate(); }; } #endif // !TEST_10 | cs |
실습 문제 11번
: Box 클래스를 작성하라.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | // main.cpp #include "test11.h" int main() { MINSEO::Box b(10, 2); b.draw(); cout << endl; b.setSize(7, 4); b.setFill('^'); b.draw(); return 0; } // test11.cpp #include "test11.h" namespace MINSEO { Box::Box(int width, int height) { setSize(width, height); fill = '*'; } void Box::setFill(char fill) { this->fill = fill; } void Box::setSize(int width, int height) { this->width = width; this->height = height; } void Box::draw() { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { cout << fill; } cout << endl; } } } // test11.h #pragma once #ifndef TEST_11 #define TEST_11 #include <iostream> using namespace std; namespace MINSEO { class Box { int width, height; char fill; public: Box(int width, int height); void setFill(char fill); void setSize(int width, int height); void draw(); }; } #endif // !TEST_11 | cs |
실습 문제 12번
: 컴퓨터 주기억장치를 모델링하는 클래스 Ram을 구현하기.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // main.cpp #include "test12.h" int main() { MINSEO::Ram ram; ram.write(100, 20); ram.write(101, 30); char res = ram.read(100) + ram.read(101); ram.write(102, res); cout << "102 번지의 값 = " << (int)ram.read(102) << endl; return 0; } // test12.cpp #include "test12.h" namespace MINSEO { Ram::Ram() { for (int i = 0; i < 100 * 1024; i++) { mem[i] = 0; } size = 100 * 1024; } Ram::~Ram() { cout << "메모리 제거됨" << endl; } char Ram::read(int address) { return mem[address]; } void Ram::write(int address, char value) { mem[address] = value; } } // test12.h #pragma once #ifndef TEST_12 #define TEST_12 #include <iostream> using namespace std; namespace MINSEO { class Ram { char mem[100 * 1024]; int size; public: Ram(); ~Ram(); char read(int address); void write(int address, char value); }; } #endif // !TEST_12 | cs |
3장 정리 문제
1) 클래스와 객체를 설명하시오
- 클래스 : 사용자 정의 자료형임. 데이터와 함수의 집합, 멤버와 멤버 함수로 구성됨.
- 객체 : 클래스에 정의된 데이터 멤버를 가지고 있음, 클래스 내 멤버 함수를 호출할 수 있는 실체
2) 객체가 생성될 때 메모리에 할당되는 것들을 설명하시오.
: 해당 클래스 내 데이터 멤버들이 할당됨. >> 멤버 변수, 멤버 함수
3) 생성자와 소멸자가 왜 필요한지 설명하시오.
- 생성자 : 객체 생성 때 호출, 객체의 초기화를 담당하기 때문에 필요함. 예를 들면 멤버 변수의 값을 특정 값으로 설정하거나, 메모리를 동적 할당 받거나, 파일을 열거나, 네트워크를 연결하는 등 객체를 사용하기 전에 피룡한 조치를 할 수 있도록 하기 위함임.
- 소멸자 : 객체 소멸 시 호출, 객체가 사용한 자원을 해제하거나 정리하는 작업 수행하기 때문에 필요함.
4) 생성자와 소멸자를 메인 함수에서 직접 호출하면 어떻게 되는지 설명하시오.
- 생성자는 직접 호출 시 임시 객체를 생성함. 그러나 임시 객체는 그 즉시 파괴되므로 실제 의미 있는 작업이 이루어지지 않음.
- 소멸자를 직접 호출하게 되면 객체가 파괴됨. 객체가 생성되고 사용되며, 소멸되는 전반적인 과정을 이룰 때 소멸자를 직접 호출 시 원하지 않는 동작을 할 수가 있기 때문에 자동으로 관리되도록 코드를 작성하는 것이 좋음.
5) 콜론 초기화를 이용하면 장점이 무엇인가?
- 생성자에서 멤버 변수를 초기화하는 데 사용됨. 코드의 가독성을 높일 수 있음. 상수나 참조형 멤버 변수를 초기화 할 수 있음.
6) 인라인 함수를 선언하는 위치는 어디가 가장 적당한가?
- 헤더 파일(.h)
7) 인라인 함수의 선언과 정의를 헤더파일과 소스파일로 분리하여 작성하면 어떻게 되는가?
- 인라인 함수는 함수 호출 지점에 컴파일러가 코드를 직접 삽입하여 실행되는 함수임. << 컴파일러가 함수 호출을 만나면 함수 정의를 찾음. 따라서 헤더파일에 작성해야 함. 분리하여 작성하게 되면 컴파일 과정에서 정의를 못 찾으므로 오류가 발생함.
8) 3.9절의 소스파일과 헤더파일을 나누는 기준을 설명하시오.
- 헤더 파일 >> 클래스 선언 부분
- 소스 파일 >> 클래스 정의 부분
++ #pragma once란?
#ifndef와 같은 헤더 파일에서 중복 포함을 방지하는 방법. #ifndef와 다르게 #pragma once 한 줄만 쓰면 중복을 방지할 수 있음.
#ifndef, #define ... 보다 조금 더 빠르게 처리될 수 있음.
다만 지원하지 않는 컴파일러도 있어 주의해야 함. << 호환성 면에서 #ifndef를 사용하는 것이 좋음.

첫댓글 #pragma once 무엇인가? 또 왜 필요한가?
정리 4,7번 다시 푸세요
수정했습니다
@신민서 7번 다시 푸세요
@Sungryul Lee 수정했습니다