C++语言程序设计

二、 各个类的定义

| 例11-34a

//算术表达式类
class arithexpr
{
public:
arithexpr(){}
virtual ~arithexpr(){}
virtual double value(double x)=0;
};

//数字类
class numexpr: public arithexpr
{
private:
double val;
public:
numexpr(double v):val(v) {}
~numexpr() {}
virtual double value(double x) {return val;}
};

//变量类
class varexpr: public arithexpr
{
public:
varexpr(){}
~varexpr() {}
virtual double value(double v) {return v;}
};

//加法类
class addexpr: public arithexpr
{
private:
arithexpr* a1;
arithexpr* a2;
public:
addexpr(arithexpr* e1, arithexpr* e2):a1(e1),a2(e2) {}
~addexpr() {delete a1;delete a2;}
virtual double value(double x) {return a1->value(x)+a2->value(x);}
};

//减法类
class subexpr: public arithexpr
{
private:
arithexpr* a1;
arithexpr* a2;
public:
subexpr(arithexpr* e1, arithexpr* e2):a1(e1),a2(e2) {}
~subexpr() {delete a1;delete a2;}
virtual double value(double x) {return a1->value(x)-a2->value(x);}
};