I currently have a base class Expr and some derivatives like AddExpr, MultExpr and NumExpr. I am trying to overload a general print() function that recursively calls the print() function of its members which are pointers to other Expr objects.
//Addition Expression
AddExpr::AddExpr( Expr* l, Expr* r ) {
left = l;
right = r;
}
string AddExpr::print() {
string s;
stringstream out;
out << "(+" << left->print() << right->print() << ")";
s = out.str();
}
NumExpr::NumExpr( string n ) {
number = atoi( n.c_str() );
}
string NumExpr::print() {
string s;
stringstream out;
out << number;
s = out.str();
return s;
}
So ultimately I want the add expression to print out a ( number + number ) if the left and right pointers are numbers, ( expression + number ), ( expression + expression ), etc. by recursively calling the print() function.
However I don't think I'm approaching this correctly as I am getting jumbled output :( I am not too familiar with pass by pointer and pass by reference, however every post that I have gone through with similar question are not quite relevant to my situation.
Here's a debug sample for calling the functions:
NumExpr* left = new NumExpr("1");
cout << left->print() << endl;
NumExpr* right = new NumExpr("2");
cout << right->print() << endl;
AddExpr* temp = new AddExpr( left, right );
cout << temp->print() << endl;
Expr* temp2 = temp;
cout << temp2->print() << endl;
This will print out 1 and 2 but has the problem on the AddExpr.
Any help is appreciated!
EDIT: the header for my expression classes:
class Expr {
public:
virtual string name();
virtual string print();
};
class AddExpr : public Expr {
public:
AddExpr(Expr* l, Expr* r);
string print();
private:
Expr* left;
Expr* right;
};
class NumExpr : public Expr {
public:
NumExpr( string v );
string print();
private:
int number;
};
Expr,AddExpr,NumExpr)? Also, what is the actual output of your sample, and what did you expect instead?return s;inAddExpr::print()