Question

So, basically I created a Float class to track down the range of floating point values used in the program. I just replace float in my program with Float. However, the output of my program changes when I use this class, but I can't figure out where is the problem.

#define real float

class Float
{
private:
real data;
static real minVal;
static real maxVal;

static void updateMinMax( real x )
{
    if ( x < minVal )
        minVal = x;

    if ( x > maxVal )
        maxVal = x;
}

public:
static real getMin() 
{
    return minVal;
}

static real getMax() 
{
    return maxVal;
}

Float()
{
    data = 0;
}

Float(real x) 
{
    data = x;
    updateMinMax(data);
}

void setFloat( real x )
{
    data = x;
    updateMinMax(data);
}

void setMaxOf( real x, real y )
{
    data = (x > y)? x : y;
    updateMinMax(data);
}

void setInt( int x )
{
    data = x;
    updateMinMax(data);
}

real getFloat() const
{
    return data;
}

operator int() const { return (int)data; }

void operator=(Float x)
{
    data = x.data;
    updateMinMax( data );
}

Float operator+(const Float& x) const
{
    updateMinMax( data + x.data );
    return Float(data + x.data);
}

void operator+=(Float x)
{
    data += x.data;
    updateMinMax( data );
}

Float operator-(const Float& x) const
{
    updateMinMax( data - x.data );
    return Float(data - x.data);
}

Float operator-() const
{
    updateMinMax( -data );
    return Float(-data);
}

void operator-=(Float x) 
{
    data -= x.data;
    updateMinMax( data );
}

Float operator*(const Float& x) const
{
    updateMinMax( data * x.data );
    return Float(data * x.data);
}

void operator*=(Float x) 
{
    data *= x.data;
    updateMinMax( data );
}

Float operator/(const Float& x) const
{
    updateMinMax( data / x.data );
    return Float(data / x.data);
}

void operator/=(Float x)
{
    data /= x.data;
    updateMinMax( data );
}

bool operator<(const Float& x) const
{
    return data < x.data;
}

bool operator<=(const Float& x) const
{
    return data <= x.data;
}

bool operator>(const Float& x) const
{
    return data > x.data;
}

bool operator>=(const Float& x) const
{
    return data >= x.data;
}

bool operator==(const Float& x) const
{
    return data == x.data;
}

friend ostream& operator<<(ostream& o, Float& x)
{
        o << x.data;
        return o;
}

friend istream& operator>>(istream& i, Float& x)
{
        i >> x.data;
        return i;
} 
};
Was it helpful?

Solution

The following test program demonstrates at least one difference between using a float and your Float class:

void test(float x)
{
    cout<<"Called with float argument"<<endl;
}
void test(int x)
{
    cout<<"Called with int argument"<<endl;
}

int main() {
    Float arg1;
    float arg2;
    test(arg1);
    test(arg2);
    return 0;
}

Output:

Called with int argument
Called with float argument
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top