반응형

문제

정수 배열을 항상 증가 순으로 유지하는 SortedArray 클래스를 작성하려고 한다. 아래의 main() 함수가 작동할 만큼만 SortedArray 클래스를 작성하고 +와 = 연산자도 작성하라

class SortedArray {
	int size; //현재 배열의 크기
	int* p;
	void sort();
public:
	SortedArray(); //p는 NULL로 size는 0으로 초기화
	SortedArray(SortedArray& src); //복사 생성자
	SortedArray(int p[], int size); //생성자, 정수 배열과 크기를 전달받음
	~SortedArray(); //소멸자
	SortedArray operator +(SortedArray& op2); //현재 배열에 op2 배열 추가
	SortedArray& operator = (const SortedArray& op2); //현재 배열에 op2 배열 복사
	void show(); //배열의 원소 출력
};

int main()
{
	int n[] = { 2,20,6 };
	int m[] = { 10,7,8,30 };
	SortedArray a(n, 3), b(m, 4), c;

	c = a + b; // +, = 연산자 작성 필요
	// + 연산자가 SortedArray 객체를 리턴하므로 복사 생성자 필요

	a.show();
	b.show();
	c.show();
}

 

결과

배열 출력 : 2 6 20

배열 출력 : 7 8 10 30

배열 출력 : 2 6 7 8 10 20 30

 

소스코드

#include<iostream>
using namespace std;
class SortedArray {
	int size; //현재 배열의 크기
	int* p;
	void sort();
public:
	SortedArray(); //p는 NULL로 size는 0으로 초기화
	SortedArray(SortedArray& src); //복사 생성자
	SortedArray(int p[], int size); //생성자, 정수 배열과 크기를 전달받음
	~SortedArray(); //소멸자
	SortedArray operator +(SortedArray& op2); //현재 배열에 op2 배열 추가
	SortedArray& operator = (const SortedArray& op2); //현재 배열에 op2 배열 복사
	void show(); //배열의 원소 출력
};
void SortedArray::sort() //정렬함수
{
	int temp;
	for (int i = 0; i < this->size - 1; i++)
	{
		for (int j = i + 1; j < this->size; j++)
		{
			if (p[i] > p[j]) {
				temp = p[i];
				p[i] = p[j];
				p[j] = temp;
			}
		}
	}
}
SortedArray::SortedArray() //생성자
{
	p = nullptr;
	size = 0;
}
SortedArray::SortedArray(SortedArray& src) //복사생성자
{
	this->size = src.size;
	this->p = new int[this->size];
	for (int i = 0; i < this->size; i++)
		this->p[i] = src.p[i];
}
SortedArray::SortedArray(int p[], int size) //매개변수 생성자
{
	this->size = size;
	this->p = new int[size];
	for (int i = 0; i < size; i++)
		this->p[i] = p[i];
}
SortedArray::~SortedArray() //소멸자
{
	delete[] p;
}
SortedArray SortedArray::operator+(SortedArray& op2)
{
	SortedArray op3;
	op3.size = this->size + op2.size;
	op3.p = new int[op3.size];
	for (int i = 0; i < op3.size; i++)
	{
		if (i < this->size)
			op3.p[i] = this->p[i];
		else
			op3.p[i] = op2.p[i - this->size];
	}
	return op3;
}
SortedArray& SortedArray::operator=(const SortedArray& op2)
{
	this->size = op2.size;
	this->p = new int[this->size];
	for (int i = 0; i < this->size; i++)
	{
		this->p[i] = op2.p[i];
	}
	return *this;
}
void SortedArray::show()
{
	this->sort(); //정렬
	cout << "배열 출력 : ";
	for (int i = 0; i < this->size; i++)
		cout << this->p[i] << ' ';
	cout << endl;
}
int main()
{
	int n[] = { 2,20,6 };
	int m[] = { 10,7,8,30 };
	SortedArray a(n, 3), b(m, 4), c;

	c = a + b; // +, = 연산자 작성 필요
	// + 연산자가 SortedArray 객체를 리턴하므로 복사 생성자 필요

	a.show();
	b.show();
	c.show();
}
반응형
반응형

문제

통계를 내는 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;
}
반응형
반응형

문제

원을 추상화한 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의 이전의 상태를 삽입하여 리턴한다. 이 때 매개변수는 사용되지 않으므로 무시해도 된다. 단지, 전위인지 후위인지 구분하는 매개 변수이다. 

 

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

반응형

+ Recent posts