I am currently working on creating my own classes to deal with numbers. My motivation is two-fold: I use Matlab a lot as a student, and I would like to have a lot of that functionality in C++. Also, I really want to learn how to use class inheritance to the fullest.
My general idea is to create a basic Number class with virtual functions, then wrap each number type in a custom class which will derive from Number. This way, I can write functions which take Numbers.
Chances are, I'm going about this completely backwards, and there are much easier, more robust, and generally better ways to do this!
First, I have defined an enumeration NumberType, each Number has one of these guys.
Now, lets look at the definition of Number, in particular, the equality operator.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class Number
{
protected:
Number(NumberType t) : type(t) {} // NumberType is an enumeration
public:
virtual ~Number(void) {}
// virtual equality operator
friend bool operator== (Number &n1, Number &n2) { return n1.isEqual(n2); }
virtual bool isEqual(Number &n) { return false; }
const NumberType type;
};
|
Now, so far I only have Bdouble and Bint, so please take a look at how I handle Bdouble's isEqual function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
bool Bdouble::isEqual(Number &n)
{
switch (n.type)
{
case NumberType::Bdouble: {
Bdouble *nPtr = (Bdouble*)&n;
return Value ==Ptr->Value;
}
case NumberType::Bint: {
Bint *nPtr = (Bint*)&n;
return Value == (int)*nPtr; // int () typecast defined in Bint
}
}
}
|
Now, I'm realizing that I will need a similar case structure for Bint. Also, every time I add a function, (and for Matlab level functionality I will need to add a LOT), I will be dealing with such case structures. Are there better ways to make classes deriving from the same base class play well together? Would a different approach altogether make sense in this case?
Any advice will be appreciated, thank you!
*edit: make some syntactical corrections to the code, and fixed where i had pasted the wrong function