Overloading '-' for array subtraction
- by Chris Wilson
I am attempting to subtract two int arrays, stored as class members, using an overloaded - operator, but I'm getting some peculiar output when I run tests. The overload definition is
Number& Number :: operator-(const Number& NumberObject)
{
for (int count = 0; count < NumberSize; count ++)
{
Value[count] -= NumberObject.Value[count];
}
return *this;
}
Whenever I run tests on this, NumberObject.Value[count] always seems to be returning a zero value. Can anyone see where I'm going wrong with this?
The line in main() where this subtraction is being carried out is
cout << "The difference is: " << ArrayOfNumbers[0] - ArrayOfNumbers[1] << endl;
ArrayOfNumbers contains two Number objects.
The class declaration is
#include <iostream>
using namespace std;
class Number
{
private:
int Value[50];
int NumberSize;
public:
Number(); // Default constructor
Number(const Number&); // Copy constructor
Number(int, int); // Non-default constructor
void SetMemberValues(int, int); // Manually set member values
int GetNumberSize() const; // Return NumberSize member
int GetValue() const; // Return Value[] member
Number& operator-=(const Number&);
};
inline Number operator-(Number Lhs, const Number& Rhs);
ostream& operator<<(ostream&, const Number&);
The full class definition is as follows:
#include <iostream>
#include "../headers/number.h"
using namespace std;
// Default constructor
Number :: Number()
{}
// Copy constructor
Number :: Number(const Number& NumberObject)
{
int Temp[NumberSize];
NumberSize = NumberObject.GetNumberSize();
for (int count = 0; count < NumberObject.GetNumberSize(); count ++)
{
Temp[count] = Value[count] - NumberObject.GetValue();
}
}
// Manually set member values
void Number :: SetMemberValues(int NewNumberValue, int NewNumberSize)
{
NumberSize = NewNumberSize;
for (int count = NewNumberSize - 1; count >= 0; count --)
{
Value[count] = NewNumberValue % 10;
NewNumberValue = NewNumberValue / 10;
}
}
// Non-default constructor
Number :: Number(int NumberValue, int NewNumberSize)
{
NumberSize = NewNumberSize;
for (int count = NewNumberSize - 1; count >= 0; count --)
{
Value[count] = NumberValue % 10;
NumberValue = NumberValue / 10;
}
}
// Return the NumberSize member
int Number :: GetNumberSize() const
{
return NumberSize;
}
// Return the Value[] member
int Number :: GetValue() const
{
int ResultSoFar;
for (int count2 = 0; count2 < NumberSize; count2 ++)
{
ResultSoFar = ResultSoFar * 10 + Value[count2];
}
return ResultSoFar;
}
Number& operator-=(const Number& Rhs)
{
for (int count = 0; count < NumberSize; count ++)
{
Value[count] -= Rhs.Value[count];
}
return *this;
}
inline Number operator-(Number Lhs, const Number& Rhs)
{
Lhs -= Rhs;
return Lhs;
}
// Overloaded output operator
ostream& operator<<(ostream& OutputStream, const Number& NumberObject)
{
OutputStream << NumberObject.GetValue();
return OutputStream;
}