반응형

문제

다음 AbstractStack은 정수 스택 클래스로서 추상 클래스이다.

class AbstractStack {
public:
	virtual bool push(int n) = 0; //스택에 n을 푸시한다. 스택이 full이면 false 리턴
	virtual bool pop(int& n) = 0; //스택에서 팝한 정수를 n에 저장하고 스택이 empty이면 리턴
	virtual int size() = 0; // 현재 스택에 저장된 개수 리턴
};

이를 상속받아 정수를 푸시, 팝하는 IntStack 클래스를 만들고 사용 사례를 보아라.

 

소스코드

#include<iostream>
using namespace std;

class AbstractStack {
public:
	virtual bool push(int n) = 0; //스택에 n을 푸시한다. 스택이 full이면 false 리턴
	virtual bool pop(int& n) = 0; //스택에서 팝한 정수를 n에 저장하고 스택이 empty이면 리턴

	virtual int size() = 0; // 현재 스택에 저장된 개수 리턴
};

class IntStack : public AbstractStack {
	int* data;
	int s, top;
public:
	IntStack(int s) {
		this->s = s;
		data = new int[s];
		top = -1;
	}
	~IntStack() { delete[] data; }
	void show() {
		for (int i = top; i >= 0; i--)
		{
			cout << data[i] << " ";
		}
		cout << endl;
	}
	virtual bool push(int n) {
		if (top + 1 >= s)return false; //top size보다 같거나 크면 false리턴
		data[++top] = n; //아니라면 값을 넣은 후 true 리턴
		return true;
	}
	virtual bool pop(int& n) {
		if (top <= -1)return false; //top이 -1보다 같거나 작다면 false리턴
		n = data[top--];
		return true;
	}
	virtual int size() {
		return top + 1; //저장된 개수 리턴 0부터 시작하므로 +1
	}
};

int main()
{
	int size, menu, push, pop;

	cout << "스택의 크기는?>> ";
	cin >> size;

	IntStack stack(size);

	while (true) {
		cout << endl << "1. 푸시 2. 팝 3. 스택보기 4. 종료" << endl << "메뉴 선택>> ";
		cin >> menu;
		switch (menu) {
		case 1:
			cout << "push 할 값>> ";
			cin >> push;
			if (stack.push(push))
				cout << "push 완료" << endl;
			else
				cout << "push할 공간이 없습니다." << endl;
			break;
		case 2:
			if (stack.pop(pop))
				cout << "pop 완료 pop한 값 : " << pop << endl;
			else
				cout << "빈 스택입니다." << endl;
			break;
		case 3:
			cout << "스택 데이터 : ";
			stack.show();
			break;
		case 4:
			cout << "종료" << endl;
			exit(1);
		default:
			cout << "잘못 입력" << endl;
			break;
		}
	}
}

 

결과

 

반응형
반응형

문제

디지털 회로에서 기본적인 게이트로 OR 게이트, AND 게이트, XOR 게이트 등이 있다.

이들은 각각 두 입력 신호를 받아 OR 연산, AND 연산, XOR 연산을 수행한 결과를 출력한다. 이 게이트들을 각각 ORGate, XORGate, ANDGate 클래스로 작성하고자 한다. ORGate, XORGate, ANDGate 클래스가 AbstractGate를 상속받도록 작성하라.

class AbstractGate { //추상 클래스
protected:
	bool x, y;
public:
	void set(bool x, bool y) { this->x = x; this->y = y; }
	virtual bool operation() = 0;
};

 

ANDGate, ORGate, XORGate를 활용하는 사례와 결과는 다음과 같다.

int main() {
	ANDGate and;
	ORGate or;
	XORGate xor;

	and.set(true, false);
	or.set(true, false);
	xor.set(true, false);
	cout.setf(ios::boolalpha); //불린 값은 "true", "false" 문자열로 출력할 것을 지시
	cout << and .operation() << endl; // AND 결과는 false
	cout << or.operation() << endl; // OR 결과는 true
	cout << xor .opeartion() << endl; // XOR 결과는 true
}

 

결과

false
true
true

 

소스코드

#include<iostream>
using namespace std;
class AbstractGate { //추상 클래스
protected:
	bool x, y;
public:
	void set(bool x, bool y) { this->x = x; this->y = y; }
	virtual bool operation() = 0;
};

class ANDGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x == true && y == true)
			return true;
		else return false;
	}
};
class ORGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x == true || y == true)
			return true;
		else return false;
	}
};
class XORGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x != y)
			return true;
		else return false;
	}
};

int main() {
	ANDGate And;
	ORGate Or;
	XORGate Xor;

	And.set(true, false);
	Or.set(true, false);
	Xor.set(true, false);
	cout.setf(ios::boolalpha); //불린 값은 "true", "false" 문자열로 출력할 것을 지시
	cout << And.operation() << endl; // AND 결과는 false
	cout << Or.operation() << endl; // OR 결과는 true
	cout << Xor.operation() << endl; // XOR 결과는 true
}

 

반응형
반응형

3~4번에 쓰이는 추상 클래스 LoopAdder 입니다.

class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

 

문제

LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 WhileLoopAdder, DowhileLoopAdder 클래스를 작성하라. while 문, do-while 문을 이용하여 합을 구하도록 calculate() 함수를 각각 작성하면 된다.

int main() {
	WhileLoopAdder whileLoop("While Loop");
	DoWhileLoopAdder doWhileLoop("Do While Loop");

	whileLoop.run();
	doWhileLoop.run();
}

 

결과

While Loop :
처음 수에서 두번째 수까지 더합니다.두 수를 입력하세요 >> 3 10
3에서 5까지의 합 = 12 입니다 Do While Loop :
처음 수에서 두번째 수까지 더합니다.두 수를 입력하세요 >> 10 20
10에서 20까지의 합 = 165

 

소스코드

#include<iostream>
using namespace std;
class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어드리는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}
class WhileLoopAdder : public LoopAdder {
	string name;
public:
	WhileLoopAdder(string name = "") :LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		int x = getX();
		int y = getY();
		while (x <= y) {
			sum += x;
			x++;
		}
		return sum;
	}
};

class DoWhileLoopAdder : public LoopAdder {
	string name;
public:
	DoWhileLoopAdder(string name = "") :LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		int x = getX();
		int y = getY();
		do {
			sum += x;
			x++;
		} while (x <= y);
		return sum;
	}
};
int main() {
	WhileLoopAdder whileLoop("While Loop");
	DoWhileLoopAdder doWhileLoop("Do While Loop");

	whileLoop.run();
	doWhileLoop.run();
}
반응형
반응형

3~4번에 쓰이는 추상 클래스 LoopAdder 입니다.

class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

 

문제

LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록  ForLoopAdder 클래스를 작성하라. ForLoopAdder 클래스의 calculate() 함수는 for 문을 이용하여 합을 구한다.

int main() {
	ForLoopAdder forLoop("For Loop");
	forLoop.run();
}

 

결과

While Loop:
처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요 >> 3 10
3에서 10까지의 합 = 52 입니다

 

소스코드

#include<iostream>
using namespace std;
class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

class ForLoopAdder : public LoopAdder {
	string name;
public:
	ForLoopAdder(string name = "") : LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		for (int i = getX(); i <= getY(); i++)
			sum += i;
		return sum;
	}
};

int main() {
	ForLoopAdder forLoop("For Loop");
	forLoop.run();
}
반응형
반응형

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 클래스를 상속받아 km를 mile(마일)로 변환하는 KmToMile 클래스를 작성하라. main() 함수와 실행 결과는 다음과 같다.

int main()
{
	KmToMile toMile(1.609344); //1mile은 1.609344km
	toMile.run();
}

 

결과

Km을 Mile로 바꿉니다. Km을 입력하세요>> 25
반환 결과 : 15.5343Mile

 

소스코드

#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 KmToMile : public Converter {
	double mile;
public:
	KmToMile(double mile) : Converter(mile) { this->mile = mile; }
	virtual double convert(double src) { return src / mile; }
	virtual string getSourceString() { return "Km"; }
	virtual string getDestString() { return "Mile"; }
};
int main()
{
	KmToMile toMile(1.609344); //1mile은 1.609344km
	toMile.run();
}

 

반응형
반응형

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 클래스를 상속받아 스택으로 작동하는 Mystack 클래스를 작성하라.

int main()
{
	MyStack mStack(100);
	int n;
	cout << "스택에 삽입할 5개의 정수를 입력하라>> ";
	for (int i = 0; i < 5; i++)
	{
		cin >> n;
		mStack.push(n); //스택에 푸시
	}
	cout << "스택용량:" << mStack.capacity() << ", 스택크기:" << mStack.length() << endl;
	cout << "스택의 모든 원소를 팝하여 출력한다>> ";
	while (mStack.length() != 0) {
		cout << mStack.pop() << ' '; //스택에서 팝
	}
	cout << endl << "스택의 현재 크기 : " << mStack.length() << endl;
}

 

결과

스택에 삽입할 5개의 정수를 입력하라>>1 3 5 7 9
스택 용량 : 100, 스택 크기 : 5
스택의 모든 원소를 팝하여 출력한다>> 9 7 5 3 1
스택의 현재 크기 : 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 MyStack : public BaseArray {
	int top = -1;
public:
	MyStack(int capacity) : BaseArray(capacity) {};
	void push(int data);
	int capacity();
	int length();
	int pop();
};
void MyStack::push(int data)
{
	if (top >= getCapacity())
	{
		cout << "스택이 가득차있습니다." << endl;
		exit(1);
	}
	put(++top, data);
}
int MyStack::capacity()
{
	return	getCapacity();
}
int MyStack::length()
{
	return top + 1;
}
int MyStack::pop()
{
	if (top <= -1) {
		cout << "스택이 비었습니다.." << endl;
		exit(1);
	}
	return get(top--);
}

int main()
{
	MyStack mStack(100);
	int n;
	cout << "스택에 삽입할 5개의 정수를 입력하라>> ";
	for (int i = 0; i < 5; i++)
	{
		cin >> n;
		mStack.push(n); //스택에 푸시
	}
	cout << "스택용량:" << mStack.capacity() << ", 스택크기:" << mStack.length() << endl;
	cout << "스택의 모든 원소를 팝하여 출력한다>> ";
	while (mStack.length() != 0) {
		cout << mStack.pop() << ' '; //스택에서 팝
	}
	cout << endl << "스택의 현재 크기 : " << mStack.length() << endl;
}
반응형

+ Recent posts