Programming Language/C,C++

C++] 명품 C++ 프로그래밍 5장 실습문제

TwinParadox 2017. 10. 27. 12:59
728x90

개인적으로 C++을 공부할 때 작성해놓았던 코드들을 찾았다.

혼자 책을 사서 독학하던 시절에, 그리고 학부생 시절에 복습하면서 했던 문제들이라서

어떤 문제들은 깔끔히 잘 정리되어 있고, 어떤 문제들은 허접한 버그가 있을 수도 있다.

확인은 해뒀지만, 확인하지 못하거나 고려해야 할 버그, 오탈자 등은 댓글을 남겨주시라. 

그간 공부한 것들을 정리하는 블로그이기 때문에 올려놓는다.



실습문제 1. 두 개의 Circle 객체를 교환하는 swap() 함수를 '참조에 의한 호출'이 되도록 작성하고 호출하는 프로그램을 작성하라.


#include <iostream>
using namespace std;
void swap(int& a, int& b)
{
	int tmp;
	tmp = a;
	a = b;
	b = tmp;
}
int main()
{
	int a, b;
	cin >> a >> b;
	swap(a, b);
	cout << a << " " << b << endl;
}




실습문제 2. 아래와 같이 원형이 주어진 bigger()를 작성하고 사용자로부터 2개의 정수를 입력받아 큰 값을 출력하는 main()을 작성하라. bigger()는 인자로 주어진 a, b가 같으면 true, 아니면 false를 리턴하고 큰 수는 big에 전달한다.


#include <iostream>
using namespace std;
bool bigger(int a, int b, int& big)
{
	if (a == b)
		return true;
	else
	{
		big = a < b ? b : a;
		return false;
	}
}
int main()
{
	int a, b, big = 0;
	cin >> a >> b;
	cout << bigger(a, b, big) << endl;
	cout << big << endl;
}




실습문제 3. 다음 Circle 클래스가 있다. Circle 객체 b를 a에 더하여 a를 키우고자 다음 함수를 작성하였다. 다음 코드를 실행하면 increaseBy() 함수는 목적대로 실행되는가? main() 함수의 목적을 달성하도록 increaseBy() 함수를 수정하라.


#include <iostream>
using namespace std;
class Circle
{
	int radius;
public:
	Circle(int r) { radius = r; }
	int getRadius() { return radius; }
	void setRadius(int r) { radius = r; }
	void show() { cout << "반지름이 " << radius << "인 원" << endl; }
};
void increaseBy(Circle& a, Circle& b)
{
	int r = a.getRadius() + b.getRadius();
	a.setRadius(r);
}
int main()
{
	Circle x(10), y(5);
	increaseBy(x, y);
	x.show();
}




실습문제 4. find() 함수의 원형은 다음과 같다. 문자열 a에서 문자 c를 찾아, 문자 c가 있는 공간에 대한 참조를 리턴한다. 만일 문자 c를 찾을 수 없다면 success 참조 매개 변수에 false를 설정한다. 물론 찾게 되면 success에 true를 설정한다. 다음 main()이 잘 실행되도록 find()를 작성하라.


#include <iostream>
#include <string.h>
using namespace std;
char& find(char a[], char c, bool& success)
{
	int size = strlen(a);
	for(int i=0;i<size;i++)
	{
		if (a[i] == c)
		{
			success = true;
			return a[i];
		}
	}
	success = false;
	return a[size];
}
int main(void)
{
	char s[] = "Mike";
	bool b = false;
	char& loc = find(s, 'M', b);
	if (b == false)
		cout << "M을 발견할 수 없다." << endl;
	else
	{
		loc = 'm';
		cout << s << endl;
	}
}




실습문제 5. 다음과 같이 선언된 정수를 저장하는 스택 클래스 MyIntStack을 구현하라. MyIntStack 스택에 저장할 수 있는 정수의 최대 개수는 10이다. MyIntStack 클래스를 활용하는 코드와 실행 결과는 다음과 같다.


#include <iostream>
using namespace std;
class MyIntStack
{
	int p[10];
	int tos;
public:
	MyIntStack();
	bool push(int n);
	bool pop(int &n);
};
MyIntStack::MyIntStack()
{
	tos = -1;
}
bool MyIntStack::push(int n)
{
	if (tos >= 9)
		return false;
	else
	{
		p[++tos] = n;
		return true;
	}
}
bool MyIntStack::pop(int &n)
{
	if (tos < 0)
		return false;
	else
	{
		n = p[tos--];
		return true;
	}
}
int main()
{
	MyIntStack a;
	for (int i = 0; i < 11; i++)
	{
		if (a.push(i))
			cout << i << " ";
		else
			cout << endl << i + 1 << " 번째 stack full" << endl;
	}
	int n;
	for (int i = 0; i < 11; i++)
	{
		if (a.pop(n))
			cout << n << " ";
		else
			cout << endl << i + 1 << " 번째 stack empty";
	}
	cout << endl;
}




실습문제 6. 문제 5번의 MyIntStack을 수정하여 다음과 같이 선언하였다. 스택에 저장할 수 있는 정수의 최대 개수는 생성자에서 주어지고 size 멤버를 유지한다. MyIntStack 클래스를 작성하라. MyIntStack 클래스를 활용하는 코드와 실행 결과는 다음과 같다.


#include <iostream>
using namespace std;
class MyIntStack
{
	int* p;
	int tos;
	int size;
public:
	MyIntStack();
	MyIntStack(int size);
	MyIntStack(MyIntStack& s);
	~MyIntStack();
	bool push(int n);
	bool pop(int &n);
};
MyIntStack::MyIntStack()
{
	tos = -1;
	size = 10;
	p = new int[size];
}
MyIntStack::MyIntStack(int size)
{
	tos = -1;
	this->size = size;
	p = new int[size];
}
MyIntStack::MyIntStack(MyIntStack& s)
{
	int i = 0;
	this->size = s.size;
	this->tos = s.tos;
	this->p = new int[size];
	for (i = 0; i <= s.tos; i++)
		this->p[i] = s.p[i];
}
MyIntStack::~MyIntStack()
{
	delete[] p;
}
bool MyIntStack::push(int n)
{
	if (tos >= 9)
		return false;
	else
	{
		p[++tos] = n;
		return true;
	}
}
bool MyIntStack::pop(int &n)
{
	if (tos < 0)
		return false;
	else
	{
		n = p[tos--];
		return true;
	}
}
int main()
{
	MyIntStack a(10);
	a.push(10);
	a.push(20);

	MyIntStack b = a;
	b.push(30);

	int n;
	a.pop(n);
	cout << "스택 a에서 팝한 값 " << n << endl;
	b.pop(n);
	cout << "스택 b에서 팝한 값 " << n << endl;
}




실습문제 7. 클래스 Accumulator는 add()함수를 통해 계속 값을 누적하는 클래스로서, 다음과 같이 선언된다. Accumulator 클래스를 구현하라. Accumulator는 다음과 같이 main() 함수에 의해 활용된다.


#include <iostream>
using namespace std;
class Accumulator
{
	int value;
public:
	Accumulator(int value);
	Accumulator& add(int n);
	int get();
};
Accumulator::Accumulator(int value)
{
	this->value = value;
}
Accumulator& Accumulator::add(int n)
{
	value += n;
	return *this;
}
int Accumulator::get()
{
	return value;
}
int main()
{
	Accumulator acc(10);
	acc.add(5).add(6).add(7);
	cout << acc.get();
}




실습문제 8. 책의 이름과 가격을 저장하는 다음 Book 클래스에 대해 물음에 답하여라. 다음과 같이 실행 오류가 발생하지 않도록, 깊은 복사 생성자를 작성하라.


#include <iostream>
#include <string.h>
#pragma warning(disable:4996)
using namespace std;
class Book
{
	char* title;
	int price;
public:
	Book(Book& b);
	Book(char* title, int price);
	~Book();
	void set(char* title, int price);
	void show() { cout << title << " " << price << "원" << endl; }
};
// 디폴트 복사 생성자
/*
Book::Book(Book& b)
{
	this->title = title;
	this->price = price;
}
*/
Book::Book(Book& b)
{
	int len = strlen(b.title);
	this->title = new char[len + 1];
	strcpy(this->title, title);
	this->price = b.price;
}
Book::Book(char* title, int price)
{
	int len = strlen(title);
	this->title = new char[len + 1];
	strcpy(this->title, title);
	this->price = price;
}
Book::~Book()
{
	delete[] title;
}
void Book::set(char* title, int price)
{
	int len = strlen(title);
	this->title = new char[len + 1];
	strcpy(this->title, title);
	this->price = price;
}
int main()
{
	Book cpp("명품C++", 10000);
	Book java = cpp;
	java.set("명품자바", 12000);
	cpp.show();
	java.show();
}
728x90
728x90