Reputation: 455
I want to implement a very simple expression calculator in C++, for example, to calculate
(3 + 2) * 8
So, I have made a base class for expression like this:
class Expression {
public:
virtual ~Expression() {}
// Returns the result of evaluating this expression.
virtual float eval() const = 0;
// Prints the expression. DO NOT evaluate before printing.
virtual void print() const = 0;
};
And then, to represent numbers, which I only care about INT and FLOAT, I've made this:
/*
* Number
*/
class Number : public Expression {
};
class IntNum : public Number {
public:
IntNum(int num) : m_value(num) {}
~IntNum() {}
float eval() const {return (float) m_value;}
void print() const {std::cout << m_value;}
protected:
int m_value;
};
class FloatNum : public Number {
public:
FloatNum(float num) : m_value(num) {}
~FloatNum() {}
float eval() const {return m_value;}
void print() const {std::cout << m_value;}
protected:
float m_value;
};
At last, I want to represent ADD, which need two operand:
/*
* Two oprand expression
*/
class TwoOpndExp : public Expression {
public:
TwoOpndExp(Expression* exp1, Expression* exp2) : m_exp1(exp1), m_exp2(exp2) {}
~TwoOpndExp() {}
protected:
Expression* m_exp1;
Expression* m_exp2;
};
/*
* Add expression
*/
class AddExp : public TwoOpndExp {
public:
float eval() const;
void print() const;
};
Here is the problem: I write
TwoOpndExp(Expression* exp1, Expression* exp2) : m_exp1(exp1), m_exp2(exp2) {}
because nobody knows what is at the both side of "+", it can be a number, simply like "1+2", or expressions involved, like "1+(2^3)". So I think the type of para for constructor should be Expression*. But, when I test it like:
IntNum* x = new IntNum(3);
FloatNum* y = new FloatNum(4.1);
AddExp* add = new AddExp(x, y);
the compiler said no constructor found for
AddExp* add = new AddExp(x, y);
I know the class will hold something as para list to find a right constructor, but, just to this problem, how to design to make it right?
This problem is available onsite:
see ass5
Thanks.
Upvotes: 0
Views: 734
Reputation: 249293
You need to add another constructor:
AddExp(Expression* exp1, Expression* exp2) : TwoOpndExp(exp1, exp2) {}
Without this, the TwoOpndExp
constructor is not inherited and therefore not available.
Upvotes: 2