반응형

문제

스택 클래스 Stack을 만들고 푸시(push)용으로 << 연산자를, 팝(pop)을 위해 >> 연산자를, 비어 있는 스택인지를 알기 위해 ! 연산자를 작성하라. 다음 코드를 main()으로 작성하라.

int main()
{
	Stack stack;
	stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
	while (true) {
		if (!stack)break; // 스택 empty
		int x;
		stack >> x; // 스택의 탑에 있는 정수 팝
		cout << x << ' ';
	}
	cout << endl;
}

 

결과

10 5 3

 

스택이란?

스택은 자료구조 중에 하나로서, 후입선출(LIFO : Last-In First-Out)구조이다. 데이터가 들어간 순서의 역순이 나오는 순서이다.

하나의 스택 스택 입력(B) 스택 입력(C) 스택 삭제(C)
    C  
  B B B
A A A A

 

 

소스코드(friend 함수 구현)

#include<iostream>
using namespace std;
class Stack {
	int stack[10];
	int top;
public:
	Stack() { top = -1; }
	friend bool operator!(Stack& sta);
	friend Stack& operator<<(Stack& sta, int n);
	friend void operator>>(Stack& sta, int& n);
};
bool operator!(Stack& sta)
{
	if (sta.top == -1)
		return true;
	return false;
}
Stack& operator<<(Stack& sta, int n)
{
	sta.stack[++sta.top] = n;
	return sta;
}
void operator>>(Stack& sta, int& n)
{
	n = sta.stack[sta.top--];
}
int main()
{
	Stack stack;
	stack << 3 << 5 << 10; // 3, 5, 10을 순서대로 푸시
	while (true) {
		if (!stack)break; // 스택 empty
		int x;
		stack >> x; // 스택의 탑에 있는 정수 팝
		cout << x << ' ';
	}
	cout << endl;
}

 

 

반응형
반응형

문제

통계를 내는 Statistics 클래스를 만들려고 한다. 데이터는 Statistics 클래스 내부에 int 배열을 동적으로 할당받아 유지한다. 다음과 같은 연산이 잘 이루어지도록 Statistics 클래스와 !, >>, <<, ~연산자 함수를 작성하라.

int main()
{
	Statistics stat;
	if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;

	int x[5];
	cout << "5 개의 정수를 입력하라>>";
	for (int i = 0; i < 5; i++)cin >> x[i];

	for (int i = 0; i < 5; i++)stat << x[i];
	stat << 100 << 200;
	~stat;

	int avg;
	stat >> avg;
	cout << "avg=" << avg << endl;
}

결과

현재 통계 데이타가 없습니다.

5 개의 정수를 입력하라 >> 1 2 3 4 5

1 2 3 4 5 100 200

avg=45

 

소스코드

#include<iostream>
using namespace std;
class Statistics {
	int* a;
	int size=0;
public:
	Statistics() { a = new int[10]; size = 0; }
	friend bool operator!(Statistics& stat);
	friend Statistics& operator<<(Statistics& stat,int x);
	friend void operator>>(Statistics& stat,int& avg);
	friend void operator~(Statistics& stat);
	~Statistics() { delete[]a; }
};
bool operator!(Statistics& stat)
{
	if (stat.size == 0) return true;
	return false;
}
Statistics& operator<<(Statistics& stat,int x)
{
	stat.a[stat.size++] = x;
	return stat;
}
void operator>>(Statistics& stat,int& avg)
{
	avg = 0;
	for (int i = 0; i < stat.size; i++)
		avg += stat.a[i];
	avg /= stat.size;
}
void operator~(Statistics& stat)
{
	for (int i = 0; i < stat.size; i++)
		cout << stat.a[i] << ' ';
	cout << endl;
}
int main()
{
	Statistics stat;
	if (!stat) cout << "현재 통계 데이타가 없습니다." << endl;

	int x[5];
	cout << "5 개의 정수를 입력하라>>";
	for (int i = 0; i < 5; i++)cin >> x[i];

	for (int i = 0; i < 5; i++)stat << x[i];
	stat << 100 << 200;
	~stat;

	int avg;
	stat >> avg;
	cout << "avg=" << avg << endl;
}
반응형
반응형

문제

문제 7번의 Circle 객체에 대해 다음 연산이 가능하도록 연산자를 구현하라. 

int main()
{
	Circle a(5), b(4);
	b = 1 + a;
	a.show();
	b.show();
}

 

결과

radius = 5 인 원

radius = 6 인 원

 

소스코드(friend 함수 구현)

#include<iostream>
using namespace std;
class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend Circle operator+(int n,Circle a);
};
Circle operator+(int n, Circle a)
{
	a.radius += n;
	return a;
}

int main()
{
	Circle a(5), b(4);
	b = 1 + a;
	a.show();
	b.show();
}

 

 

반응형
반응형

문제

원을 추상화한 Circle 클래스는 간단히 아래와 같다.

class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
};

 

다음 연산이 가능하도록 연산자를 프렌드 함수로 작성하라

int main()
{
	Circle a(5), b(4);
	++a;
	b = a++;
	a.show();
	b.show();
}

 

결과

radius = 7 인 원

radius = 6 인 원

 

소스코드

#include<iostream>
using namespace std;
class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	void show() { cout << "radius = " << radius << " 인 원" << endl; }
	friend void operator++(Circle& a);
	friend Circle& operator++(Circle& a, int b);
};

void operator++(Circle& a)
{
	++a.radius;
}
Circle& operator++(Circle& a,int b)
{
	Circle temp = a;
	a.radius++;
	return temp;
}
int main()
{
	Circle a(5), b(4);
	++a;
	b = a++;
	a.show();
	b.show();
}

설명 : 전위, 후위 연산자 모두 참조 매개변수를 사용한다. 전위 연산자인 ++a 의 경우 리턴 값이 필요없으므로 참조매개변수로 a.radius값을 1증가시킨다. 후위 연산자인 경우 매개 변수를 가지도록 선언이 되며, 후위 연산자는 그 줄의 코드가 실행된 후 증가를 시키기 때문에 참조매개변수를 이용해 a.radius의 값은 증가시켜주지만 temp의 이전의 상태를 삽입하여 리턴한다. 이 때 매개변수는 사용되지 않으므로 무시해도 된다. 단지, 전위인지 후위인지 구분하는 매개 변수이다. 

 

오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.

반응형
반응형

문제

2차원 행렬을 추상화한 Matrix 클래스를 활용하는 다음 코드가 있다.

int main()
{
	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1,2,3,4 };
	a >> x;
	b << y;
	for (int i = 0; i < 4; i++)cout << x[i] << ' ';
	cout << endl;
	b.show();
}

 

결과

4 3 2 1

Matrix = { 1 2 3 4 }

 

1. <<, >> 연사자 함수를 Matrix 멤버 함수로 구현하라.

#include<iostream>
using namespace std;

class Matrix {
	int a[4];
public:
	Matrix() {};
	Matrix(int a, int b, int c, int d) {
		this->a[0] = a;
		this->a[1] = b;
		this->a[2] = c;
		this->a[3] = d;
	}
	void show();
	void operator>>(int x[]);
	void operator<<(int y[]);
};
void Matrix::show()
{
	cout << "Matrix = { " << a[0] << ' ' << a[1] << ' ' << a[2] << ' ' << a[3] << " }" << endl;
}
void Matrix::operator>>(int x[])
{
for(int i =0;i<4;i++)
	x[i] = a[i];
}
void Matrix::operator<<(int y[])
{
for(int i= 0 ;i<4;i++)
	a[i] = y[i];
}
int main()
{
	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1,2,3,4 };
	a >> x;
	b << y;
	for (int i = 0; i < 4; i++)cout << x[i] << ' ';
	cout << endl;
	b.show();
}

 

2. <<, >> 연산자 함수를 Matrix의 프렌드 함수로 구현하라.

#include<iostream>
using namespace std;

class Matrix {
	int a[4];
public:
	Matrix() {};
	Matrix(int a, int b, int c, int d) {
		this->a[0] = a;
		this->a[1] = b;
		this->a[2] = c;
		this->a[3] = d;
	}
	void show();
	friend void operator>>(Matrix a, int x[]);
	friend void operator<<(Matrix& b,int y[]);
};
void Matrix::show()
{
	cout << "Matrix = { " << a[0] << ' ' << a[1] << ' ' << a[2] << ' ' << a[3] << " }" << endl;
}
void operator>>(Matrix a,int x[])
{
	for (int i = 0; i < 4; i++)
		x[i] = a.a[i];
}
void operator<<(Matrix& b, int y[])
{
	for (int i = 0; i < 4; i++)
		b.a[i] = y[i];
}
int main()
{
	Matrix a(4, 3, 2, 1), b;
	int x[4], y[4] = { 1,2,3,4 };
	a >> x;
	b << y;
	for (int i = 0; i < 4; i++)cout << x[i] << ' ';
	cout << endl;
	b.show();
}

 

오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.

반응형
반응형

문제

2차원 행렬을 추상화한 Matrix 클래스를 작성하고, show() 멤버 함수와 다음 연산이 가능하도록 연산자를 모두 구하여라.

int main() {
	Matrix a(1, 2, 3, 4), b(2, 3, 4, 5), c;
	c = a + b;
	a += b;
	a.show(); b.show(); c.show();
	if (a == c)
		cout << "a and c are same " << endl;
}

 

결과

Matrix = { 3 5 7 9 }

Matrix = { 2 3 4 5 }

Matrix = { 3 5 7 9 }

a and c are the same

 

1. 연산자 함수를 Matrix의 멤버 함수로 구현하라.

#include<iostream>
using namespace std;
class Matrix {
	int a, b, c, d;
public:
	Matrix() {};
	Matrix(int a, int b, int c, int d);
	void show();
    Matrix& operator+(Matrix& a);
    Matrix& operator+=(Matrix& a);
    bool operator==(Matrix b);
};

Matrix::Matrix(int a, int b, int c, int d)
{
	this->a = a;
	this->b = b;
	this->c = c;
	this->d = d;
}

void Matrix::show()
{
	cout << "Matrix = { " << this->a << " " << this->b << " " << this->c << " " << this->d << " }" << endl;
}

Matrix& Matrix::operator+(Matrix& a)
{
	Matrix b;
	b.a = this->a + a.a;
	b.b = this->b + a.b;
	b.c = this->c + a.c;
	b.d = this->d + a.d;
	return b;
}

Matrix& Matrix::operator+=(Matrix& a)
{
	this->a += a.a;
	this->b += a.b;
	this->c += a.c;
	this->d += a.d;
	return *this;
}

bool Matrix::operator==(Matrix b)
{
	if (this->a == b.a && this->b == b.b && this->c == b.c && this->d == b.d)
		return true;
	return false;
}

int main() {
	Matrix a(1, 2, 3, 4), b(2, 3, 4, 5), c;
	c = a + b;
	a += b;
	a.show(); b.show(); c.show();
	if (a == c)
		cout << "a and c are same " << endl;
}

 

2. 연산자 함수를 Matrix의 프렌드 함수로 구현하라.

#include<iostream>
using namespace std;
class Matrix {
	int a, b, c, d;
public:
	Matrix() {};
	Matrix(int a, int b, int c, int d);
	void show();
    friend Matrix operator+(Matrix a, Matrix b);
	friend Matrix operator+=(Matrix& a, Matrix b);
	friend bool operator==(Matrix a, Matrix b);
};
Matrix::Matrix(int a, int b, int c, int d)
{
	this->a = a;
	this->b = b;
	this->c = c;
	this->d = d;
}
void Matrix::show()
{
	cout << "Matrix = { " << this->a << " " << this->b << " " << this->c << " " << this->d << " }" << endl;
}
Matrix operator+(Matrix a, Matrix b)
{
	Matrix c;
	c.a = a.a + b.a;
	c.b = a.b + b.b;
	c.c = a.c + b.c;
	c.d = a.d + b.d;
	return c;
}
Matrix operator+=(Matrix& a, Matrix b)
{
	a.a += b.a;
	a.b += b.b;
	a.c += b.c;
	a.d += b.d;
	return a;
}
bool operator ==(Matrix a, Matrix b)
{
	if (a.a == b.a && a.b == b.b && a.c == b.c && a.d == b.d)
		return true;
	return false;
}
int main() {
	Matrix a(1, 2, 3, 4), b(2, 3, 4, 5), c;
	c = a + b;
	a += b;
	a.show(); b.show(); c.show();
	if (a == c)
		cout << "a and c are same " << endl;
}
반응형
반응형

다음 main()에서 Color 클래스는 3요소(빨강, 초록, 파랑)로 하나의 색을 나타내는 클래스이다. (4장 실습 문제 1번 참고). + 연사자로 색을 더하고, == 연사자로 색을 비교하고자 한다. 실행결과를 참고하여 Color 클래스와 연산자, 그리고 프로그램을 완성하라.

int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show();

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

 

결과

255 0 255

보라색 맞음

 

1. + 와 == 연사자를 Color 클래스의 멤버 함수로 구현하라.

#include<iostream>
using namespace std;
class Color {
	int r, g, b;
public:
	Color() {};
	Color(int r, int g, int b) { this->r = r; this->g = g; this->b = b; };
	void show();
    Color operator+(Color b);
	bool operator==(Color f);
    };
Color Color::operator+(Color b)
{
	Color a;
	a.r = this->r + b.r;
	a.g = this->g + b.g;
	a.b = this->b + b.b;
	return a;
}
bool Color::operator==(Color f)
{
	if (this->r == f.r && this->g == f.g && this->b == b)
		return true;
	return false;
}
int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show();

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

 

2. +와 == 연사자를 Color 클래스의 프렌드 함수로 구현하라.

#include<iostream>
using namespace std;
class Color {
	int r, g, b;
public:
	Color() {};
	Color(int r, int g, int b) { this->r = r; this->g = g; this->b = b; };
	void show();
    friend Color operator+(Color a, Color b);
	friend bool operator==(Color a, Color b);
};
void Color::show()
{
	cout << this->r << " " << this->g << " " << this->b << endl;
}
Color operator+(Color a, Color b)
{
	Color c;
	c.r = a.r + b.r;
	c.g = a.g + b.g;
	c.b = a.b + b.b;
	return c;
}
bool operator==(Color a, Color b)
{
	if (a.r == b.r && a.g == b.g && a.b == b.b)
		return true;
	return false;
}
int main() {
	Color red(255, 0, 0), blue(0, 0, 255), c;
	c = red + blue;
	c.show();

	Color fuchsia(255, 0, 255);
	if (c == fuchsia)
		cout << "보라색 맞음";
	else
		cout << "보라색 아님";
}

 

오류 또는 수정 사항 궁금한 점 있으시면 댓글로 남겨주세요.

반응형

+ Recent posts