我有以下抽象基类:
class Function {
virtual double Eval(double x) const = 0;
};
我希望能够使用 f * g 或 f->operator *(g) 等表达式,其中 f 和 g 是类 Function 的具体对象,在我的主文件中,例如当我想计算定积分时这样我就可以写:
AnIntegrationMethod(f*g);
我想出的一个相当简单的方法包括声明一个 Product 类(仅显示头文件,实现很明显):
class Product: public Function {
public: Product(Function *g, Function *f);
~Product();
virtual double Eval(double x) const; //return _g->Eval(x)*_f->Eval(x)
private: Function *_g; Function *_f;
};
然后在我的任何函数中
#include "Product.h"
class ConcreteFunction: public Function {
public:
ConcreteFunction();
~ConcreteFunction();
virtual double Eval(double x) const;
Function* operator*(Function *f) {return new Product(this, f);}
};
这实际上适用于简单的东西,但问题是运算符 * 仅在基类的单个派生类中定义,而不是为每个可能的派生类定义。这意味着,例如,如果我有一个代表数学函数的具体对象 f,我可以调用 f->operator *g 但如果我想再次调用operator * 来获取对象 (f->operator * g)- >operator * f 我无法这样做,因为函数 f* g 没有将 * 运算符定义为 f。
我想我应该直接在我的基类中定义运算符 * ,但是我无法弄清楚如何实现该运算符,因为我真的不知道如何获得产品的正确 Eval 函数,因为我无法使用 Product 类现在,在 Function 类本身中使用从 Function 类派生的 Product 类是没有意义的。我想我也很困惑,写如下内容一般是否正确:
Function* Function::operator*(Function *f) {
Function *g;
...
//operations that allow g to be have the right Eval function
//which should of the sort this->Eval(x) * f->Eval(x)
...
return g;
}
任何有关如何继续的提示或建议都将受到赞赏。我的水平很基础,我已经编程两个月了。