Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <sstream>
- using namespace std;
- class Exp {
- public:
- Exp() {};
- virtual string pretty() = 0;
- virtual int eval() = 0;
- virtual Exp* simp() { return this; }
- };
- class IntExp : public Exp {
- public:
- int val;
- public:
- IntExp(int _val) {
- val = _val;
- }
- string pretty() {
- stringstream ss;
- ss << val; // Konvertierung von Integer return ss.str(); // in einen String } };
- return ss.str();
- }
- int eval() {
- return this->val;
- }
- };
- class PlusExp : public Exp {
- public:
- Exp *e1;
- Exp *e2;
- public:
- PlusExp(Exp *_e1, Exp *_e2) {
- e1 = _e1;
- e2 = _e2;
- }
- string pretty() {
- return "(" + e1->pretty() + " + " + e2->pretty() + ")"; // 1 + 2 * 3 != (1 + 2) * 3
- }
- int eval() {
- return this->e1->eval() + this->e2->eval(); //rekursion
- }
- Exp* simp() {
- //teile
- this->e1 = this->e1->simp();
- this->e2 = this->e2->simp();
- //0 + e => e
- if (this->e1->eval() == 0)
- return this->e2;
- //e + 0 => e
- if (this->e2->eval() == 0)
- return this->e1;
- return this; //nicht einfacher gemacht
- }
- };
- class MultExp : public Exp {
- public:
- Exp *e1;
- Exp *e2;
- public:
- MultExp(Exp *_e1, Exp *_e2) {
- e1 = _e1;
- e2 = _e2;
- }
- string pretty() {
- return e1->pretty() + " * " + e2->pretty(); //kp was hier der Fehler ist
- }
- int eval() {
- return this->e1->eval() * this->e2->eval();
- }
- Exp* simp() {
- //Teile vereinfachen
- this->e1 = this->e1->simp();
- this->e2 = this->e2->simp();
- //1 * e => e
- if (this->e1->eval() == 1)
- return this->e2;
- //e * 1 => e
- if (this->e2->eval() == 1)
- return this->e1;
- return this; //nicht einfacher gemacht
- }
- };
- int main() {
- //tests
- Exp *e = new MultExp(new PlusExp(new IntExp(1), new IntExp(2)), new IntExp(3));
- cout << e->pretty() << endl;
- cout << e->eval() << endl;
- cout << e->simp()->pretty() << endl;
- Exp *f = new MultExp(new PlusExp(new IntExp(0), e), new IntExp(1));
- cout << f->pretty() << endl;
- cout << f->eval() << endl;
- cout << f->simp()->pretty() << endl;
- return 0x0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement