Я не могу понять почему результат показывается правильно а выражение пустым.
Вот что на экране я виже:
(( + ( * )) — (( + 0 / ))
Result = 47
Куда исчезли цифры?
Я понимаю, что создаются временные объекты, но почему результат правильный а стринги пустые?
Спасибо.
Вот мой код
Main
void main()
{
//(10 + 6*7) - (20 + 30) / 10
CompositeOperand composExpr1('*', NumericOperand(Node(6)), NumericOperand(Node(7)));
CompositeOperand composExpr2('+', NumericOperand(Node(10)), composExpr1);
CompositeOperand composExpr3('+', NumericOperand(Node(20)), NumericOperand(Node(30)));
CompositeOperand composExpr4('/', composExpr3, NumericOperand(Node(10)));
CompositeOperand eq('-', composExpr2, composExpr4);
eq.print();
cout << endl << "Result = " << eq.evaluate() << endl;
}
class ArithExpr
{
public:
virtual void print() const = 0;
virtual int evaluate() const = 0;
};
class Node
{
private:
string m_name;
int m_value;
public:
Node(string name, int value) { m_name = name; m_value = value; }
Node(int value) { m_value = value; m_name = to_string<int>(value); }
string getName() const { return m_name; }
int getValue() const { return m_value; }
};
class NumericOperand : public ArithExpr
{
private:
Node m_operand;
public:
NumericOperand(Node operand) { m_operand = operand; }
virtual void print() const { cout << m_operand.getName(); }
virtual int evaluate() const { return m_operand.getValue(); }
};
class CompositeOperand : public ArithExpr
{
private:
char m_operator;
ArithExpr& m_left;
ArithExpr& m_right;
public:
CompositeOperand(char op, ArithExpr& left, ArithExpr& right) { m_operator=op; m_left=left; m_right=right; }
int evaluate() const
{
int left = m_left.evaluate();
int right = m_right.evaluate();
int res = calculate(m_operator, left, right);
return res;
}
virtual void print() const
{
cout << "(";
m_left.print();
cout << " " << m_operator << " ";
m_right.print();
cout << ")";
}
private:
int calculate(char op, int left, int right) const
{
int res = 0;
switch(op)
{
case '+':
res = left + right;
break;
case '-':
res = left - right;
break;
case '*':
res = left * right;
break;
case '/':
res = left / right;
break;
}
return res;
}
};