# c++虚函数实现计算表达式

### 于是我们可以构造虚函数来解决这样的问题

( ( 1 + 2 ) × 3 + 4 ) ÷ 6 \left( \left( 1+2\right) \times 3+4\right) \div 6

### getvalue()

#include<iostream>
#include<algorithm>

using namespace std;

class expression
{
public:
float value;
expression()
{
value = 0;
}
virtual float getvalue() = 0;
};

//所有的派生类（表达式）都有一个返回float型的getvalue()返回该基类派生类的value
class TerminalExpression: public expression
{
public:
virtual float getvalue()
{
return value;
}
};

{
public:
expression* l;                                  //基类的指针可以new派生类的对象！！！
expression* r;
virtual float getvalue()
{
value = l->getvalue() + r->getvalue();
return value;
}
};

class MultiplyExpression: public expression
{
public:
expression* l;
expression* r;
virtual float getvalue()
{
value = l->getvalue() * r->getvalue();
return value;
}
};

class DivisionExpression: public expression
{
public:
expression* l;
expression* r;
virtual float getvalue()
{
value = l->getvalue() / r->getvalue();
return value;
}
};

//((1 + 2)*3 + 4)/6 = 2.16667
int main()
{
p->l = new TerminalExpression;
p->l->value = 1;
p->r = new TerminalExpression;
p->r->value = 2;                                    //左右两侧均为terminal赋值

MultiplyExpression *q = new MultiplyExpression;
q->l = p;                                           //左侧的值为表达式p
q->r = new TerminalExpression;
q->r->value = 3;

n->l = new MultiplyExpression;
n->l = q;                                           //左侧的值为表达式q
n->r = new TerminalExpression;
n->r->value = 4;

DivisionExpression *d = new DivisionExpression;
d->l = n;                                           //左侧的值表达式为n
d->r = new TerminalExpression;
d->r->value = 6;

cout<<d->getvalue()<<endl;
return 0;
}


06-10 9717

08-18 1080
04-15 712
11-21 3478
07-24 1742
05-19
06-05 5816
07-06 1万+
01-19 6462
12-18