fding
fding

Reputation: 455

Represent expression calculation c++ (Polymorphism design)

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:

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-088-introduction-to-c-memory-management-and-c-object-oriented-programming-january-iap-2010/assignments/

see ass5

Thanks.

Upvotes: 0

Views: 734

Answers (1)

John Zwinck
John Zwinck

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

Related Questions