I am trying to write a numerical integration program. My program should obtain a mathematical function in c++ syntax via cin, and then use it in my c++ integration function. For example: I enter the function x*x+3*x with variable x into the console as a string, and my program uses this as the function to integrate. Thanks for any replies
class Functor {
public:
virtualdoubleoperator()(double) = 0;
};
class Plus : public Functor{
private:
Functor* left;
Functor* right;
public:
Plus(Functor* left, Functor* right) : left(left), right(right) {}
virtualdoubleoperator() (double x) {
return *left(x) + *right(x);
}
};
//other operators...
class Constant : public Functor {
private:
double value;
public:
Constant(double value) : value(value) {}
virtualdoubleoperator() (double) {
return value;
}
};
class Variable : public Functor {
public:
virtualdoubleoperator() (double x) {
return x;
}
};
That's of course neither the only nor necessarily the best way to do it, but it works. How to get your expression into this tree form is left as an exercise to you, though it would probably be easiest to convert to polish notation first.
Nope. In an initializer list the language allows identifiers with the same name because they can be distinguished. var(/*something*/) is always an instance variable, and /*something*/(var) is always an argument. Note that this only applies if there is a constructor argument AND a instance variable of the same name, I'm not sure about the behavior of the compiler if only one of them is there.
Thank you hanst99 , I appreciate that you took the time to help me, but I honestly don't understand a thing you wrote :(. I just started into classes and I don't know anything about functors. Does anyone know a simpler/different way? thanks
That's the simple way. At least I don't think this could be done much simpler than this.
Functor in this case has nothing to do with the mathematical concept, it just means "object that provides the () operator", so you can write myFunctor(*args*) instead of myFunctor.doSomething(*args*).