#include <iostream>
class Resistor
{
float R;
public:
Resistor& setR(float r) { R=r; return *this; }
float getI(float E) { return E/R; }
float getE(float I) { return R*I; }
float getP(float I) { return I*getE(I); }
Resistor() :R(0) {}
Resistor(float r) :R(r) {}
};
int main() {
Resistor r(5);
std::cout << "Resistor(5).getE(0.5) = " << r.getE(0.5f) << " V" << std::endl;
std::cout << "Resistor(100).getI(12) = " << r.setR(100).getI(12) << " A" << std::endl;
std::cout << "Resistor(1200).getP(0.01) = " << r.setR(1200).getP(0.01) << " W" << std::endl;
return 0;
}
Ok, so here is a silly one from me.
Let Variables be a map of string to float:
typedef std::map<std::string,float> Variables;
Let Operation be an abstract class that has the following declaration:
struct Operation {
virtual float evaluate(const Variables& vars) = 0;
};
Implement Add, Sub, Mul, Div, Const, Var that extend Operation so that the following example is possible:
// Create expression: (A+10)*(1/(B-3))
Mul expression(
Add( Var("A"), Const(10) ),
Div( Const(1),
Sub(Var("B"),Const(3))
)
);
// Create variable map
Variables vars;
vars["A"] = 2.5;
vars["B"] = 7;
// Evaluate expression using variables in vars map
float result = expression.evaluate(vars);
You may add abstract methods to Operation.
Edited by nooc9, 28 October 2009 - 07:45 AM.