인프런 커뮤니티 질문&답변
[06:07] 코드 중복되는 부분 한 곳에서 수정 할 수 있게 생각해보는 부분
해결된 질문
작성
·
258
0
안녕하세요?
강의 한 번 다보고 복습중입니다.
뒤에서 배운거 이용해서 코딩해봤는데요. 문제를 푸는 게 아니라 더 복잡하게 만든 거 같지만 ㅠㅠ
printResult 함수에서 반복문 돌면서 그 안에서 연산자 오버로딩해서 사칙연산 수행하려고 했는데
잘 안되네요. 다음강의 복습하고 다시 살펴 보겠습니다.
1. Operator클래스를 만들어서 연산자를 한 곳에서 관리하려고 했고
2. getOperator, printResult 함수에서는 반복문을 이용해서 Operator클래스안에 있는 연산자들과
비교해서 일치하면 해당 연산을 수행하게 하려고 했습니다.
감사합니다.
<실행화면>

<코드>
// Chapter5.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
class Operator
{
private:
char op[5];
public:
Operator()
: op{ '+', '-', '*', '/' , '%'}
{}
friend std::ostream& operator << (std::ostream& out, const Operator& oper)
{
for (auto& elem: oper.op)
out << elem << " ";
return out;
}
char& operator[](int index)
{
return op[index];
}
/*Operator& operator+(const Operator& oper)
{
return op + oper.op[1];
}*/
};
int getInt();
char getOperator(Operator& oper);
void printResult(int x, char op, int y, Operator& oper);
int main()
{
Operator oper;
//cout << op << endl;
int x = getInt();
char op = getOperator(oper);
int y = getInt();
printResult(x, op, y, oper);
return 0;
}
int getInt()
{
int x;
cout << "input an integer : " << endl;
cin >> x;
std::cin.ignore(32767, '\n');
return x;
}
char getOperator(Operator& oper)
{
//cout << oper[1] << endl;
//for (unsigned i = 0; i < 5; ++i)
for(;;)
{
char op;
cout << "Enter an operator(+, -, *, /, %) : " << endl;
cin >> op;
std::cin.ignore(32767, '\n');
//if (op == oper[i])
if (op == oper[0] || op == oper[1] || op == oper[2] || op == oper[3] || op == oper[4])
{
return op;
}
else
{
cout << "invalid operator try again" << endl;
}
}
}
void printResult(int x, char op, int y, Operator& oper)
{
cout << "result : " << endl;
/*for (int i = 0; i < 5; ++i)
{
if (op == oper[i])
cout << x << " " << op << " " << y << " = " << x oper[i] y << endl;
}*/
if (op == oper[0])
{
cout << x << " " << op << " " << y << " = " << x+y << endl;
}
else if (op == oper[1])
{
cout << x << " " << op << " " << y << " = " << x - y << endl;
}
else if (op == oper[2])
{
cout << x << " " << op << " " << y << " = " << x * y << endl;
}
else if (op == oper[3])
{
cout << x << " " << op << " " << y << " = " << x / y << endl;
}
else if (op == oper[4])
{
cout << x << " " << op << " " << y << " = " << x % y << endl;
}
else
{
cout << "Invalid operator" << endl;
}
}
감사합니다.





