--> Frank Masingill wrote to Cliff Rhodes <--
FM>My Borland compiler choked on the line below (the only
FM>place your code where it flagged an error.
FM> return static_cast(Num1) / Num2;
Your compiler doesn't recognize the new C++ casts. These were
introduced to enforce better type checking. I think Borland 4.5 and
later support them.
FM> So I changed it to
FM>
FM> return (float)(Num1) / Num2;
That's exactly the right thing to do!
FM> And the compilation sailed right through. My IDE help
FM>did not identify "static_cast" as a keyword or recognize
FM> yet you spoke of this expression as though it were
FM>C++ terminology.
FM>
FM> If, instead, your intention was simply to call my
FM>attention to it in order for ME to substitute the correct
FM>terminology then happily, I did so. Am I correct in
FM>assessing your intent here?
No, I was using one of the newer bell's and whistles of C++. Since
your compiler doesn't support the new style of casts, just continue to
do it like you would in C.
There are a few more improvements you could make to your code. For
instance, you should make simple procedures 'inline'. What that means
is that the compiler will insert the code to do the procedure directly
in place of a function call. That makes operation a little faster.
You can make a member function inline by including its body in the
class definition--see below. You can also use the inline keyword--but
I'll let you follow up on that if you are interested.
You also should declare 'const' all the member functions that don't
change the data in the class (Num1 and Num2). This allows the compiler
to use const instances of the class if needed. It's a good habit to
into even if you may never use a const instance.
So, here's another look at the Calc class:
class Calc {
private:
int Num1, Num2; //private data members
public:
Calc(int i, int j) { Num1 = i; Num2 = j } // inline constructor
// Make Add(), Subtract() and Multiply() const and inline
int Add(void) const { return Num1 + Num2; }
int Subtract(void) const { return Num1 - Num2; }
int Multiply(void) const { return Num1 * Num2; }
int Divide(int &r) const; //return quotient of Nums 1 and 2
float Divide(void) const; //return quotient as floating point
};
int Calc::Divide(int &r) const
{
// Returns the quotient of Num1 and Num2. The remainder is
// returned through the reference r.
if(Num2 != 0) // Make sure not 0!
{
r = Num1 % Num2; // Calculate the remainder
return Num1 / Num2; // Return the quotient
}
// You would actually add other code here to signal a divide by
// zero error, but to keep it simple...
r = 0; // Didn't do the division if here
return 0; // Return 0 quotient if divide by zero
}
float Calc::Divide(void) const
{
if(Num2 != 0)
return (float) Num1 / Num2; // Old style cast
// Or use new cast: return static_cast(Num1) / Num2;
return 0.0; // If divide by 0, just return 0.
}
--- Maximus/2 3.01
---------------
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)
|