C++语言程序设计

| 例11-34b

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

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

//乘方类
class powexpr: public arithexpr
{
private:
arithexpr* a1;
arithexpr* a2;
public:
powexpr(arithexpr* e1, arithexpr* e2):a1(e1),a2(e2) {}
~powexpr() {delete a1;delete a2;}
virtual double value(double x) {return pow(a1->value(x),a2->value(x));}
};

//算术函数类
typedef double (*func)(double);
class funcexpr: public arithexpr
{
private:
func f;
arithexpr* arg;
public:
funcexpr (func fn,arithexpr* a):arg(a),f(fn){}
~ funcexpr () {delete arg;}
virtual double value(double x) {return f(arg->value(x));}
};