C++/Integer class
Expert: Zlatko - 3/30/2010
QuestionI am trying to write an integer class that allows the user to enter a number 10 digits long. I am trying to overload the [] operator so that the index returns the digit in position i, where i=0 is the least significant digit. I am having problems with this part of the code.
I have written the rest of the code. So far it will accept a number, then it prints the number entered instead of each digit separately.
AnswerHello Jacob.
I assume that you are storing the number in your class as an integer, and that you want to return the digit as an integer.
Lets say that mValue is the integer stored in you class.
The operator[] is like this:
int operator[](int index)
{
int x = mValue / (int)pow(10.0, index);
return x % 10;
}
The first line divides the integer mValue by a power of 10 so that the desired digit is at the end.
The second line picks off the last digit and returns it.
You can combine the two lines into one.
You will need to include math.h to get the pow function.
Does that make sense? Feel free to follow up if you don't understand something.
Some things to investigate:
What happens if mValue is negative ?
What happens if your index value is greater than the number of digits in mValue ?
Best regards
Zlatko