1. 문제

 

8. 다수의 클래스를 선언하고 활용하는 간단한 문제이다. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 4개의 클래스 Add, Sub, Mul, Div를 만들고자 한다. 이들은 모두 공통으로 다음 멤버를 가진다.

- int 타입 변수 a, b : 피연산자

- void setValue(int x, int y) 함수 : 매개 변수 x, y를 멤버 a, b에 복사

- int calculate() 함수 : 연산을 실행하고 결과 리턴

 

 main() 함수는 Add, Sub, Mul, Div 클래스 타입의 객체 a, s, m, d를 생성하고, 아래와 같이 키보드로부터 두 개의 정수와 연산자를 입력받고, a, s, m, d 객체 중에서 연산을 처리할 객체의 setValue() 함수를 호출한 후, calculate()를 호출하여 결과를 화면에 출력한다. 프로그램은 무한 루프를 돈다.

 

 

2. 결과

 

 

 

3. 코드

 

//	Calculator.cpp

#include <iostream>
#include <string>

using namespace std;

class Add {
	int a;
	int b;
public :
	void setValue(int x, int y);
	int calculate();
};
class Sub {
	int a;
	int b;
public :
	void setValue(int x, int y);
	int calculate();
};
class Mul {
	int a;
	int b;
public :
	void setValue(int x, int y);
	int calculate();
};
class Div {
	int a;
	int b;
public :
	void setValue(int x, int y);
	int calculate();
};
void Add::setValue(int x, int y) {
	a = x; b = y;
}
int Add::calculate() {
	return a+b;
}

void Sub::setValue(int x, int y) {
	a = x; b = y;
}
int Sub::calculate() {
	return a-b;

}void Mul::setValue(int x, int y) {
	a = x; b = y;
}
int Mul::calculate() {
	return a*b;

}void Div::setValue(int x, int y) {
	a = x; b = y;
}
int Div::calculate() {
	return a/b;
}

int main() {

	char cal[10]; char *p;
	int x, y; 

	while(1) { 
		cout << "두 정수와 연산자를 입력하세요>>";
		cin.getline( cal, 20);
		x = stoi( strtok( cal, " ") );
		y = stoi( strtok( NULL, " ") );
		p = strtok( NULL, "");
		if( strcmp( p, "+") == 0 ) {  
			Add a; 
			a.setValue(x, y); 
			cout << a.calculate() << endl; }
		else if( strcmp( p, "-") == 0 ) {
			Sub s;
			s.setValue(x, y);
			cout << s.calculate() << endl; }
		else if( strcmp( p, "*") == 0 ) {
			Mul m;
			m.setValue(x, y);
			cout << m.calculate() << endl; }
		else if( strcmp( p, "/") == 0 ) {
			Div d;
			d.setValue(x, y);
			cout << d.calculate() << endl; }
	}
}

 

 

4. 설명

 

strtok()를 이용하여서 두 수를 int형 변수에 저장한 후 연산자도 char*형 변수 p에 저장한 후 p에 따라 해당하는 사칙연산 클래스  변수를 생성하고 사칙연산이 실행되도록 구현하였습니다.

 

(2)번 때문에 구현부가 짧은 멤버함수도 선언부와 구현부를 나누어 작성하였습니다.

 

※ 이 문제는 띄어쓰기를 기준으로 3값을 구분하므로 cin >> x >> y >> p로 입력을 받으셔도 굳이 strtok()함수를 사용하지 않으셔도 원하는 결과를 얻을 수 있습니다.

 

+ Recent posts