반응형

1~2번에 쓰이는 단위변환 추상 클래스 Converter입니다.

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};

 

문제

Converter 클래스를 상속받아 달러를 원화로 환산하는 WonToDollar 클래스를 작성하라. main() 함수와 실행 결과는 다음과 같다.

int main()
{
	WonToDallar wd(1010); //1달러에 10101원
	wd.run();
}

 

결과

원을 달러로 바꿉니다. 원을 입력하세요>> 10000
변환 결과 : 9.90099달러

 

소스코드

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};
class WonToDallar : public Converter
{
	int krw;
public:
	WonToDallar(int krw) : Converter(krw) { this->krw = krw; }
	virtual double convert(double src) {
		return src / krw;
	}
	virtual string getSourceString() {
		return "원";
	}
	virtual string getDestString() {
		return "달러";
	}
};
int main()
{
	WonToDallar wd(1010); //1달러에 10101원
	wd.run();
}

 

반응형
반응형

문제

비행기 예약 프로그램을 작성하라. 이 문제는 여러 개의 클래스와 객체들을 다루는 연습을 위한 것이다. 클래스 사이의 상속 관계는 없다. 항공사 이름은 '한성항공' 이고, 8개의 좌석을 가진 3대의 비행기로 서울 부산 간 운항 사업을 한다. 각 비행기는 하루에 한 번만 운항하며 비행 시간은 7시, 12시, 17시이다. 비행기 예약 프로그램은 다음의 기능을 가진다.

예약 : 비행시간, 사용자 이름, 좌석 번호를 입력받아 예약한다.
취소 : 비행 시간, 사용자의 이름, 좌석 번호를 입력받고 예약을 취소한다.
예약 보기 : 예약된 좌석 상황을 보여준다.

 

결과

 

힌트

클래스는 AirlineBook, Schedule, Seat 3개이며, main함수는 별도의 cpp파일에 작성한다.

즉, 클래스는 헤더파일로 작성한다.

또한 사용자 입력을 전담하는 Console 클래스를 작성한다.

 

AirlineBook 클래스 - Schedule 객체 3개 생성, 예약 시스템 작동
Schedule클래스  - 하나의 스케쥴을 구현하는 클래스. 8개의 Seat객체 생성. Seat객체에 예약, 취소, 보기 등 관리
Seat클래스 - 하나의 좌석을 구현하는 클래스. 예약자 이름 저장. 좌석에 대한 예약, 취소, 보기 등 관리
Console클래스 - 메뉴를 출력하는 함수, 사용자로부터 메뉴 선택, 비행 시간, 사용자 이름, 좌석 번호 등을 입력받는 멤버 함수들을 구현, 멤버들은 static으로 작성하는 것이 좋다.

 

소스코드

Air.h

#include<iostream>
#include<string>
using namespace std;
class Console {
public:
	static int menu() {
		cout << "예약:1, 취소:2, 보기:3, 끝내기:4>>";
		int inputmenu;
		cin >> inputmenu;
		return inputmenu;
	}
	static int chotime() {
		int inputtime;
		while (true) {
			cout << "07시:1, 12시:2, 17시:3>>";
			cin >> inputtime;
			if (1 <= inputtime && inputtime <= 3)
				break;
			cout << "존재하지 않는 시간대입니다." << endl;
		}
		return inputtime;
	}
	static int setseat()
	{
		int setnumber;
		while (true) {
			cout << "좌석 번호>>";
			cin >> setnumber;
			if (1 <= setnumber && setnumber <= 8)
				break;
			cout << "존재하지 않는 번호입니다." << endl;
		}
		return setnumber;
	}
	static string setname()
	{
		string name;
		cout << "이름 입력>>";
		cin >> name;
		return name;
	}
};

class Seat {
	string name; //예약자 이름
public:
	Seat() { name = "___"; }
	void setname(string name) { this->name = name; } //예약시 이름변경
	void cancelseat() { name = "___"; } //예약 취소시 원래대로
	string getname() { return name; } //예약자 이름출력
};

class Schedule {
	string time;
	Seat* seat;
public:
	Schedule() { seat = new Seat[8]; } //좌석 8개
	~Schedule() { delete[]seat; }
	void settime(string time) { this->time = time; } //시간 이름
	string gettime() { return time; }
	string getname(int seatnumber) { return seat[seatnumber].getname(); }
	void setseat(int seatnumber, string name) { seat[seatnumber].setname(name); }
	void cancle(int seatnumber) { seat[seatnumber].cancelseat(); }
	void showseat() { //좌석 출력
		for (int i = 0; i < 8; i++)
			cout << i+1<<seat[i].getname() << "\t";
		cout << endl;
	}
};

class AirlineBook {
	Schedule* schedule;
public:
	AirlineBook() {
		schedule = new Schedule[3];
		schedule[0].settime("07시 : ");
		schedule[1].settime("12시 : ");
		schedule[2].settime("17시 : ");
	}
	~AirlineBook() { delete[]schedule; }
	void mainmenu();
};


void AirlineBook::mainmenu()
{
	while (true)
	{
		cout << endl;
		int chotime, menu, seat;
		string name;
		menu = Console::menu();
		switch (menu)
		{
		case 1:
			chotime = Console::chotime()-1;
			schedule[chotime].showseat();
			seat = Console::setseat()-1;
			if (schedule[chotime].getname(seat) != "___") {
				cout << "이미 예약된 좌석입니다." << endl;
				break;
			}
			name = Console::setname();
			schedule[chotime].setseat(seat, name);
			break;
		case 2:
			chotime = Console::chotime()-1;
			schedule[chotime].showseat();
			seat = Console::setseat()-1;
			if (schedule[chotime].getname(seat) == "___") {
				cout << "빈 좌석입니다." << endl;
				break;
			}
			name = Console::setname();
			if (schedule[chotime].getname(seat)!=name) {
				cout << "예약자의 이름과 다릅니다." << endl;
				break;
			}
			schedule[chotime].cancle(seat);
			break;
		case 3:
			for (int i = 0; i < 3; i++)
			{
				cout << schedule[i].gettime();
				schedule[i].showseat();
			}
			break;
		case 4:
			cout << "예약 시스템을 종료합니다." << endl;
			exit(1);
			break;
		default:
			cout << "메뉴 잘못 입력" << endl;
			break;

		}
	}
}

 

main.cpp

#include <iostream>
#include <string>
#include "Air.h"
using namespace std;


int main()
{
	AirlineBook* air = new AirlineBook();
	cout << "*** 한성항공에 오신것을 환영합니다. ***" << endl;
	air->mainmenu();
	delete[]air;
}

 

반응형
반응형

문제

다음 그림과 같은 상속 구조를 갖는 클래스를 설계한다.

모든 프린터는 모델명(model), 제조사(manufacturer), 인쇄 매수(printedCount), 인쇄 종이 잔량(availableCount)을 나타내는 정보와 print(int pages) 멤버 함수를 가지며, print()가 호출할 때마다 pages 매의 용지를 사용한다. 잉크젯 프린터는 잉크 잔량(availableInk) 정보와 printInkJet(int pages) 멤버 함수를 추가적으로 가지며, 레이저 프린터는 토너 잔량(availableToner) 정보와 역시 printLaser(int pages) 멤버 함수를 추가적으로 가진다. 각 클래스에 적절한 접근 지정으로 멤버 변수와 함수, 생성자, 소멸자를 작성하고, 다음과 같이 실행되도록 전체 프로그램을 완성하라. 잉크젯 프린터 객체와 레이저 프린터 객체를 각각 하나만 동적 생성하여 시작한다.

 

결과

 

소스코드

#include<iostream>
#include<string>
using namespace std;
class Printer {
	string model;		 //모델
	string manufacturer; //제조사
	int printedCount;	 //인쇄 매수
	int availableCount;  //인쇄 잔량
public:
	Printer(string m, string f, int ac) {
		model = m;
		manufacturer = f;
		availableCount = ac;
	}
	string getmodel() { return model; }				//모델명 리턴
	string getmanufacturer() { return manufacturer; }  //제조사 리턴
	int getavailableCount() { return availableCount; } //인쇄 잔량 리턴

	void print(int pages) {
		printedCount = pages;
		availableCount -= printedCount;
	}

};
class IPrinter : public Printer {
	int availbleInk;	 //잉크 잔량
public:
	IPrinter(string m, string f, int aCount, int aInk) : Printer(m, f, aCount) { availbleInk = aInk; }
	int getIavailableCount() { return getavailableCount(); }
	void printInkJet(int pages) {
		availbleInk -= pages;
		print(pages);
	}
	int getavailbleInk() { return availbleInk; }
	void show() {
		cout << getmodel() << ", " << getmanufacturer()
			<< ", 남은 종이" << getavailableCount() << ", 남은 잉크" << getavailbleInk() << endl;
	}
};
class RPrinter : public Printer {
	int availableToner;	 //토너 잔량
public:
	RPrinter(string m, string f, int aCount, int aToner) : Printer(m, f, aCount) { availableToner = aToner; } //토너 초기화
	int getRavailableCount() { return getavailableCount(); }
	void printLaser(int pages) {
		availableToner -= pages;
		print(pages);
	}
	int getavailableToner() { return availableToner; }
	void show() {
		cout << getmodel() << ", " << getmanufacturer()
			<< ", 남은 종이" << getavailableCount() << ", 남은 토너" << getavailableToner() << endl;
	}
};
int main()
{
	IPrinter IP("Officejet V40", "HP", 5, 10);
	RPrinter RP("SCX-6x45", "삼성전자", 3, 20);
	char q = 'y';
	int printer, pages;
	cout << "현재 작동중인 2대의 프린터는 아래와 같다" << endl;
	cout << "잉크젯 : ";
	IP.show();
	cout << "레이저 : ";
	RP.show();

	while (true) {
		cout << endl;
		cout << "프린터 (1:잉크젯, 2:레이저)와 매수 입력>>";
		cin >> printer >> pages;
		if (!(printer == 1 || printer == 2)) //프리터 1번 또는 2번을 선택하지 않았다면
			cout << "프린터가 존재하지 않습니다." << endl;
		else
		{
			if (printer == 1) { //잉크젯 선택
				if (IP.getIavailableCount() < pages) //용지가 부족할 경우
					cout << "용지가 부족하여 프린트할 수 없습니다." << endl;
				else {
					IP.printInkJet(pages);
					cout << "프린터하였습니다.\n";
				}
			}
			else { //그 외 선택
				if (RP.getRavailableCount() < pages) //용지가 부족할 경우
					cout << "용지가 부족하여 프린트할 수 없습니다." << endl;
				else {
					RP.printLaser(pages);
					cout << "프린터하였습니다.\n";
				}
			}
		}
		IP.show();
		RP.show();
		cout << "계속 프린트 하시겠습니까?(y/n)>>";
		cin >> q; //n이면 루프 종료
		if (q == 'y')
			continue;
		else //그이외에의 값 종료 while(q != 'n')을 쓰셔도 됩니다.
			exit(1); 
	}
}
반응형
반응형

문제

아래와 같은 BaseMemory 클래스를 상속받는 ROM(Read Only Memory), RAM 클래스를 작성하라. BaseMemory에 필요한 코드를 수정 추가하여 적절히 완성하라.

class BaseMemory {
	char* men;
protected:
	BaseMemory(int size) {
		men = new char[size];
	}
};

 

ROM은 읽기 전용 메모리이므로 작동 중에 값을 쓸 수가 없기 때문에, 공장에서 생산할 때 생산자가 요청한 데이터로 초기화하는데 이 작업을 굽는다(burn)라고 한다. 그러므로 ROM은 반드시 생성자에서 burn 작업이 일어나야 한다.

다음은 ROM과 RAM 메모리ㅣ를 생성하고 사용하는 사례이다. ROM의 0번지에서 4번지까지 읽어 RAM 메모리의 0~4번지에 쓰고, 다시 RAM 메모리의 값을 화면에 출력한다. 전체 프로그램을 완성하라.

int main()
{
	char x[5] = { 'h','e','l','l','o' };
	ROM biosROM(1024 * 10, x, 5); //10KB의 ROM메모리, 배열 x로 초기화됨
	RAM mainMemory(1024 * 1024); //1MB의 RAM메모리

	//0번지에서 4번지까지의 biosROM에서 읽어 mainMemory에 복사
	for (int i = 0; i < 5; i++)
		mainMemory.write(i, biosROM.read(i));
	for (int i = 0; i < 5; i++)
		cout << mainMemory.read(i);
}

 

결과

hello

 

소스코드

#include<iostream>
using namespace std;

class BaseMemory {
	char* men;
protected:
	BaseMemory(int size) {
		men = new char[size];
	}
	~BaseMemory() { delete [] men; }
	void setmen(int i, int data) { men[i] = data; }
	char getmen(int i) { return men[i]; }
};
class ROM : public BaseMemory {
public:
	ROM(int Memory, char x[], int size) : BaseMemory(Memory) {
		for (int i = 0; i < size; i++)
		{
			setmen(i, x[i]);
		}
	};
	char read(int i) { return getmen(i); }
};
class RAM : public BaseMemory {
public:
	RAM(int Memory) : BaseMemory(Memory) {};
	char read(int i) { return getmen(i); }
	void write(int i, char data) { setmen(i, data); }
};
int main()
{
	char x[5] = { 'h','e','l','l','o' };
	ROM biosROM(1024 * 10, x, 5); //10KB의 ROM메모리, 배열 x로 초기화됨
	RAM mainMemory(1024 * 1024); //1MB의 RAM메모리

	//0번지에서 4번지까지의 biosROM에서 읽어 mainMemory에 복사
	for (int i = 0; i < 5; i++)
		mainMemory.write(i, biosROM.read(i));
	for (int i = 0; i < 5; i++)
		cout << mainMemory.read(i);
}
반응형
반응형

문제 5, 6번에 적용되는 BaseArray 클래스는 다음과 같다.

class BaseArray {
private:
	int capacity; // 배열의 크기
	int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
	BaseArray(int capacity = 100)
	{
		this->capacity = capacity; mem = new int[capacity];
	}
	~BaseArray() { delete[]mem; }
	void put(int index, int val) { mem[index] = val; }
	int get(int index) { return mem[index]; }
	int getCapacity() { return capacity; }
};

 

문제

BaseArray를 상속받아 큐처럼 작동하는 MyQueue클래스를 작성하라. MyQueue를 활용하는 사례는 다음과 같다.

int main()
{
	MyQueue mQ(100);
	int n;
	cout << "큐에 삽입할 5개의 정수를 입력하라>> ";
	for (int i = 0; i < 5; i++)
	{
		cin >> n;
		mQ.enqueue(n); //큐에 삽입
	}
	cout << "큐의 용량 : " << mQ.capacity() << ", 큐의 크기 : " << mQ.length() << endl;
	cout << "큐의 원소를 순서대로 제거하여 출력한다>> ";
	while (mQ.length() != 0) {
		cout << mQ.dequeue() << ' '; //큐에서 제거하여 출력
	}
	cout << endl << "큐의 현재 크기 : " << mQ.length() << endl;
}

 

결과

큐에 삽입할 5개의 정수를 입력하라>> 1 3 5 7 9

큐의 용량:100, 큐의 크기:5

큐의 원소를 순서대로 제거하여 출력한다>> 1 3 5 7 9

큐의 현재 크기 : 0

 

소스코드

#include<iostream>
using namespace std;
class BaseArray {
private:
	int capacity; // 배열의 크기
	int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
	BaseArray(int capacity = 100)
	{
		this->capacity = capacity; mem = new int[capacity];
	}
	~BaseArray() { delete[]mem; }
	void put(int index, int val) { mem[index] = val; }
	int get(int index) { return mem[index]; }
	int getCapacity() { return capacity; }
};
class MyQueue : public BaseArray {
	int front, rear;
public:
	MyQueue(int capacity) : BaseArray(capacity) { front = 0; rear = 0; }
	void enqueue(int data);
	int dequeue();
	int capacity();
	int length();
};
void MyQueue::enqueue(int data)
{
	if (rear >= getCapacity()) {
		cout << "큐가 가득찼습니다." << endl;
		exit(1);
	}
	put(++rear, data);
}
int MyQueue::dequeue()
{
	if (front == rear) {
		cout << "꺼낼 데이터가 없습니다." << endl;
		exit(1);
	}
	--rear;
	return get(++front);
}
int MyQueue::capacity()
{
	return getCapacity();
}
int MyQueue::length()
{
	return rear;
}
int main()
{
	MyQueue mQ(100);
	int n;
	cout << "큐에 삽입할 5개의 정수를 입력하라>> ";
	for (int i = 0; i < 5; i++)
	{
		cin >> n;
		mQ.enqueue(n); //큐에 삽입
	}
	cout << "큐의 용량 : " << mQ.capacity() << ", 큐의 크기 : " << mQ.length() << endl;
	cout << "큐의 원소를 순서대로 제거하여 출력한다>> ";
	while (mQ.length() != 0) {
		cout << mQ.dequeue() << ' '; //큐에서 제거하여 출력
	}
	cout << endl << "큐의 현재 크기 : " << mQ.length() << endl;
}
반응형
반응형

문제 3, 4번에 적용되는 2차원 상의 한 점을 표현하는 Point 클래스가 있다.

class Point {
	int x, y;
public:
	Point(int x, int y) { this->x = x; this->y = y; }
	int getX() { return x; }
	int getY() { return y; }
protected:
	void move(int x, int y) {
		this->x = x; this->y = y;
	}
};

 

문제

다음 main() 함수가 실행되도록 Point 클래스를 상속받는 ColorPoint 클래스를 작성하고, 전체 프로그램을 완성하라.

int main() {
	ColorPoint zeroPoint;
	zeroPoint.show();

	ColorPoint cp(5, 5);
	cp.setPoint(10, 20);
	cp.setColor("BLUE");
	cp.show();
}

 

결과

BLACK색으로 ( 0, 0 )에 위치한 점입니다.

BLUE색으로 ( 10, 20 )에 위치한 점입니다.

 

소스코드

#include<iostream>
#include<string>
using namespace std;
class Point {
	int x, y;
public:
	Point(int x, int y) { this->x = x; this->y = y; }
	int getX() { return x; }
	int getY() { return y; }
protected:
	void move(int x, int y) { this->x = x; this->y = y; }
};
class ColorPoint : public Point {
	string color;
public:
	ColorPoint(int x = 0, int y = 0, string color = "BLACK") : Point(x, y) {
		this->color = color;
	}
	void show();
	void setPoint(int x, int y);
	void setColor(string color);
};
void ColorPoint::show()
{
	cout << color << "색으로 ( " << getX() << ", " << getY() << " )에 위치한 점입니다." << endl;
}
void ColorPoint::setPoint(int x, int y)
{
	move(x, y);
}
void ColorPoint::setColor(string color)
{
	this->color = color;
}
int main() {
	ColorPoint zeroPoint;
	zeroPoint.show();

	ColorPoint cp(5, 5);
	cp.setPoint(10, 20);
	cp.setColor("BLUE");
	cp.show();
}

 

반응형
반응형

문제 1, 2번에 적용도는 원을 추상화한 Circle 클래스가 있다.

class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	int getRadius() { return radius;}
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};

 

문제

다음과 같이 배열을 선언하여 다음 실행 결과가 나오도록 Circle을 상속받은 NamedCircle 클래스와 main() 함수 등 필요한 함수를 작성하라.

NamedCircle pizza[5];

 

결과

5 개의 정수 반지름과 원의 이름을 입력하세요

1>> 5 크림피자

2>> 8 치즈피자

3>> 25 대왕피자

4>> 30 블랙홀피자

5>> 15 마늘피자

 

소스코드

#include<iostream>
#include<string>
using namespace std;
class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	int getRadius() { return radius; }
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};
class NamedCircle : public Circle {
	string name;
public:
	NamedCircle() {};
	string getName() { return name; }
	void setName(string name) { this->name = name; }
};
int main()
{
	NamedCircle pizza[5];
	int r;
	string name;
	int count = 0;
	cout << "5 개의 정수 반지름과 원의 이름을 입력하세요" << endl;
	for (int i = 0; i < 5; i++)
	{
		cout << i + 1 << ">>";
		cin >> r >> name;
		pizza[i].setRadius(r);
		pizza[i].setName(name);
	}
	for (int i = 0; i < 4; i++)
	{
		if (pizza[i].getRadius() < pizza[i + 1].getRadius())
			count = i + 1;
	}
	cout << "가장 면적이 큰 피자는 " << pizza[count].getName() << "입니다." << endl;
}

설명

Circle과 같은 원리인 함수 NamedCircle클래스에 선언해 준 후 Circle의 멤버 함수와 NamedCircle의 멤버 함수를 이용하여 값들을 저장하고 반지름의 크기만 비교하여 가장 큰 곳의 인덱스를 기억하여 출력한다.

반응형
반응형

문제 1, 2번에 적용도는 원을 추상화한 Circle 클래스가 있다.

class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	int getRadius() { return radius;}
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};

 

문제

다음 코드가 실행되도록 Circle을 상속받는 NamedCircle 클래스를 작성하고 전체 프로그램을 완성하라.

int main()
{
	NamedCircle waffle(3, "waffle"); //반지름이 3이고 이름이 waffle인 원
	waffle.show();
}

 

결과

반지름이 3인 waffle

 

소스코드

#include<iostream>
#include<string>
using namespace std;
class Circle {
	int radius;
public:
	Circle(int radius = 0) { this->radius = radius; }
	int getRadius() { return radius;}
	void setRadius(int radius) { this->radius = radius; }
	double getArea() { return 3.14 * radius * radius; }
};
class NamedCircle : public Circle {
	string name;
public:
	NamedCircle(int r, string name);
	void show();
};
NamedCircle::NamedCircle(int r, string name)
{
	setRadius(r);
	this->name = name;
}
void NamedCircle::show()
{
	cout << "반지름이 " << getRadius() << "인 " << name << endl;
}
int main()
{
	NamedCircle waffle(3, "waffle"); //반지름이 3이고 이름이 waffle인 원
	waffle.show();
}

설명

Circle을 상속받으므로 Circle에 존재하는 반지름 설정함수 setRadius(), 반지름 출력함수 getRadius()을 사용할 수 있다.

반응형
반응형

문제

정수 배열을 항상 증가 순으로 유지하는 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