반응형

문제

정수 배열을 항상 증가 순으로 유지하는 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();
}
반응형

+ Recent posts