0. 알아두자!!
1. 디폴트 매개 변수를 가진 add() 함수를 작성하고 프로그램을 완성하라.
<실행화면>
<소스코드>
#include <iostream>
using namespace std;
int add(int arr[], int size = 1) {
int sum = 0;
for (int i = 1; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int a[] = { 1,2,3,4,5 };
int b[] = { 6,7,8,9,10 };
int c = add(a, 5);
int d = add(b, 5);
cout << c << endl;
cout << d << endl;
return 0;
}
2. Person 클래스의 생성자 함수를 디폴트 매개 변수를 가진 하나의 생성자로 완성하라.
<실행화면>
<소스코드>
#include <iostream>
#include <string>
using namespace std;
class Person {
int id;
double weight;
string name;
public:
Person(int id = 1, string name = "Grace", double weight = 20.5) {
this->id = id;
this->name = name;
this->weight = weight;
}
void show() {
cout << id << ' ' << weight << ' ' << name << endl;
}
};
int main() {
Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);
grace.show();
ashley.show();
helen.show();
return 0;
}
3. big() 함수를 디폴트 매개 변수를 가진 하나의 함수로 작성하라.
<실행화면>
<소스코드>
#include <iostream>
using namespace std;
int big(int a, int b, int max = 100) {
int bigger = a > b ? a : b;
if (bigger > max) {
return max;
}
else
return bigger;
}
int main() {
int x = big(3, 5);
int y = big(300, 60);
int z = big(30, 60, 50);
cout << x << ' ' << y << ' ' << z << endl;
return 0;
}
4. 다음 클래스에 중복된 생성자를 디폴트 매개 변수를 가진 하나의 생성자로 작성하고 테스트 프로그램을 작성하라.
<실행화면>
<소스코드>
#include <iostream>
using namespace std;
class MyVector {
int* mem;
int size;
public:
MyVector(int n = 100, int val = 0); // 디폴트 매개 변수는 선언부에만 작성
~MyVector() { delete[] mem; }
void show();
};
MyVector::MyVector(int n, int val) { // 중복 정의 방지
mem = new int[n];
size = n;
for (int i = 0; i < size; i++) {
mem[i] = val;
}
}
void MyVector::show()
{
for (int i = 0; i < size; i++)
cout << mem[i] << ' ';
cout << endl;
}
int main() {
int x, y;
x = 10, y = 5;
MyVector Vector1; // 0을 100번 출력
MyVector Vector2(x, y);
Vector1.show();
Vector2.show();
return 0;
}
5. 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라/.
<실행화면>
<소스코드>
#include <iostream>
using namespace std;
class ArrayUtility {
public:
//ArrayUtility();
static void intToDouble(int source[], double dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}
}
static void doubleToInt(double source[], int dest[], int size) {
for (int i = 0; i < size; i++) {
dest[i] = source[i];
}
}
};
int main()
{
int x[] = { 1, 2, 3, 4, 5 };
double y[5];
double z[] = { 9.9, 8.8, 7.7, 6.6, 5.6 };
ArrayUtility::intToDouble(x, y, 5);
for (int i = 0; i < 5; i++)
cout << y[i] << ' ';
cout << endl;
ArrayUtility::doubleToInt(z, x, 5);
for (int i = 0; i < 5; i++)
cout << x[i] << ' ';
cout << endl;
}
6. 동일한 크기의 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility2 클래스를 만들고, 이 클래스를 이용하여 아리 결과와 같이 출력되도록 프로그램을 완성하라.
<실행화면>-
<소스코드>
#include <iostream>
using namespace std;
class ArrayUtility {
public:
// s1과 s2 연결한 새로운 배열을 동적 생성하고 포인터 리턴
static int* concat(int s1[], int s2[], int size);
// s1에서 s2에 있는 숫자를 모두 삭제한 새로운 동적 배열을 동적 생성하여 리턴
// 리턴하는 배열의 크기는 retSize에 전달. retSize == 0이면 NULL 전달
static int* remove(int s1[], int s2[], int size, int& retSize);
};
int* ArrayUtility::concat(int s1[], int s2[], int size) {
int* arr = new int[size];
for (int i = 0; i < size/2; i++) {
arr[i] = s1[i];
}
for (int i = 0; i < size/2; i++) {
arr[i + (size/2)] = s2[i];
}
return arr;
}
int* ArrayUtility::remove(int s1[], int s2[], int size, int& retSize) {
if (retSize == 0) return NULL;
int* arr = new int[size];
for (int i = 0; i < size / 2; i++) {
bool isSame = false; // 매 반복마다 초기화
for (int j = 0; j < size / 2; j++) {
if (s1[i] == s2[j]) {
isSame = true; // s1에 s2의 원소가 있으면 true 마킹
break; // 반복문 탈출
}
}
if (isSame == false) arr[retSize++] = s1[i];
}
return arr;
}
int main() {
int y[5];
int x[5];
cout << "정수를 5 개 입력하라. 배열 x에 삽입한다>>";
for (int i = 0; i < 5; i++)
cin >> x[i];
cout << "정수를 5 개 입력하라. 배열 y에 삽입한다>>";
for (int i = 0; i < 5; i++)
cin >> y[i];
cout << "합친 정수 배열을 출력한다" << endl;
int* s3 = ArrayUtility::concat(x, y, 10);
for (int i = 0; i < 10; i++) {
cout << s3[i] << ' ';
}
cout << endl;
delete[] s3;
int cnt = 0;
int* s4 = ArrayUtility::remove(x, y, 10, cnt);
cout << "배열 x[]에서 y[]를 뺀 결과를 출력한다. 개수는 " << cnt << endl;
for (int i = 0; i < cnt; i++) {
cout << s4[i] << ' ';
}
cout << endl;
delete[] s4;
}
7. 다음과 같은 static 멤버를 가진 Random 클래스를 완성하라. 그리고 Random 쿨래스를 이용하여 다음과 같이 랜덤한 값을 출력하는 main() 함수도 작성하라. main() 에서 Random 클래스의 seed() 함수를 활용하라.
class Random {
public:
static void seed() { srand((unsigned)time(0)); }
static int nextInt(int min = 0, int max = 32767);
static char nextAlphabet();
static double nextDouble();
};
<실행화면>
<소스코드>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
class Random {
public:
static void seed() { srand((unsigned)time(0)); }
static int nextInt(int min = 0, int max = 32767) {
int range = max - min + 1;
int r = rand() % range + min;
return r;
}
static char nextAlphabet() {
char c = rand() % 52; // 대소문자 각 26개
if (c < 26) return 'a' + c; // 소문자
else return 'A' + c - 26; // 대문자
}
static double nextDouble() {
return (double)rand() / 32767;
}
};
int main() {
Random::seed();
cout << "1에서 100까지 랜덤한 정수 10개를 출력합니다" << endl;
for (int i = 0; i < 10; i++) {
cout << Random::nextInt(1, 100) << ' ';
}
cout << endl;
cout << "알파벳을 랜덤하게 10개를 출력합니다" << endl;
for (int i = 0; i < 10; i++) {
cout << Random::nextAlphabet() << ' ';
}
cout << endl;
cout << "랜덤한 실수를 10개를 출력합니다" << endl;
for(int i=0; i<10; i++){
if (i == 5) cout << endl;
cout << Random::nextDouble() << ' ';
}
cout << endl;
return 0;
}
8. 디버깅에 필요한 정보를 저장하는 Trace 클래스를 만들어보자. 저자의 경험에 의하면, 멀티테스크 프로그램을 개발하거나 특별한 환경에서 작업할 때, Visual Studio의 디버거와 같은 소스 레벨 디버거를 사용하지 못하는 경우가 더러 있었고, 이때 실행 도중 정보를 저장하기 위해 Trace 클래스를 만들어 사용하였다. Trace클래스를 활용하는 다음 프로그램과 결과를 참고하여 Trace 클래스를 작성하고 전체 프로그램을 완성하라. 디버깅 정보는 100개로 제한한다.
<실행화면>
<소스코드>
#include <iostream>
#include <string>
using namespace std;
class Trace {
public:
static int max, num;
static string trace[100][2];
static void put(string tag, string info); // tag: 태그, info: 디버깅 정보
static void print(string tag);
};
int Trace::max = 100;
int Trace::num = 0;
string Trace::trace[100][2];
void Trace::put(string function, string info) {
if (num < max) { // 디버깅 정보 최대 100개로 제한
trace[num][0] = function;
trace[num++][1] = info; // info까지 저장 후 인덱스 번호 증가
}
else {
cout << "디버깅 정보 100개 초과" << endl;
return;
}
}
void Trace::print(string tag = "all") {
if (tag == "all") {
cout << "----- 모든 Trace 정보를 출력합니다. -----" << endl;
for (int i = 0; i < num; i++) {
cout << trace[i][0] << ":" << trace[i][1] << endl;
}
}
else {
cout << "----- " << tag << "태그의 Trace 정보를 출력합니다. -----" << endl;
for (int i = 0; i < num; i++) {
if (trace[i][0] == tag) {
cout << trace[i][0] << ":" << trace[i][1] << endl;
}
}
}
}
void f() {
int a, b, c;
cout << "두 개의 정수를 입력하세요>>";
cin >> a >> b;
Trace::put("f()", "정수를 입력 받았음"); // 디버깅 정보 저장
c = a + b;
Trace::put("f()", "합 계산"); // 디버깅 정보 저장
cout << "합은 " << c << endl;
}
int main() {
Trace::put("main()", "프로그램 시작합니다"); // 디버깅 정보 저장
f();
Trace::put("main()", "종료"); // 태그, 디버깅 정보
Trace::print("f()"); // f() 태그를 가진 디버깅 정보 모두 출력
Trace::print(); // 모든 디버깅 정보 출력
return 0;
}
9. 게시판 프로그램을 작성해보자. 멀티테스킹의 경우 여러 사용자들이 게시판에 글을 올리기 때문에 게시판 객체는 전체 하나만 있어야 한다. 그러므로 게시판 객체의 멤버들은 static으로 작성한다. 다음은 게시판 기능을 하는 Board 클래스를 활용하는 main() 코드이다. 실행 결과를 참고하여 Board 클래스를 만들고 전체 프로그램을 완성하라. static 연습이 목적이기 때문에 게시판 기능을 글을 올리는 기능과 게시글을 모두 출력하는 기능으로 제한하고 main()도 단순화하였다.
<실행화면>
<소스코드>
#include <iostream>
#include <string>
using namespace std;
class Board {
public:
static int max, num;
static string board[100];
static void add(string text) {
if (num < max) board[num++] = text;
else {
cout << "게시판이 포화 상태입니다." << endl;
return;
}
}
static void print() {
cout << "*************** 게시판입니다. ***************" << endl;
for (int i = 0; i < num; i++) {
cout << i << ": " << board[i] << endl;
}
cout << endl;
}
};
int Board::max = 100;
int Board::num = 0;
string Board::board[100];
int main()
{
Board::add("중간고사는 감독 없는 자율 시험입니다.");
Board::add("코딩 라운지 많이 이용해 주세요");
Board::print();
Board::add("진소린 학생이 경진대회 입상하였습니다. 축하해주세요");
Board::print();
}
[객체지향언어1] 명품 C++ Programming 8장 실습 문제 일부 (0) | 2025.06.16 |
---|---|
[객체지향언어1] 명품 C++ Programming 7장 실습 문제 (0) | 2025.06.15 |
[객체지향언어1] 명품 C++ Programming 5장 실습 문제 (1) | 2025.04.27 |
[객체지향언어1] 명품 C++ 프로그래밍 4장 Open Challenge (0) | 2025.04.13 |
[객체지향언어1] 명품 C++ Programming 3장 실습 문제 (0) | 2025.04.08 |