C++ Question Function Overloading

Thanks, Vlad for helping me solve this!
Last edited on
First of all you can not enter 0029 because the value will be stored as 29. That is the computer does not see a difference between 29 and 0029.:) Also you need not to have an int array in your class.
The correct definition of the subscript operator will look the following way

int MyInteger::operator []( unsigned int index ) const
   const int base = 10;
   int digit;
   unsigned int i = 0; 
   int value = num;

   do { digit = value % base; } while ( ( i++ != index ) && ( value /= base )  );

   return ( ( i == index + 1 ) ? digit : -1 );

I did not test the code but hope it will work if does not contain a typo.

Last edited on
I understand that, though what I don't understand is for example, i'm not so worried about starting with 0's, although it would be nice to be able to reverse if it started with 0's such as 0029, going to 9200 as well, however, it's supposed to be reversed of what you enter, so if I entered 418, I would get 814, and the a[3] for example would be a -1, but what i'm receiving is 0 instead of -1 that should be there. Also I don't understand how that ties into powers, maybe i'm missing something.
I uodated the function. Look it one more especially the condition of the do-while.
Ahh I see that now trying to see how to implement that, but trying I get a bunch of errors. Mainly on line 15 of my code above when I try to replace my messy code with yours to test at least to get some know how.

This is what I get:

\myInteger\main.cpp|20|error: prototype for 'int MyInteger::operator[](unsigned int) const' does not match any in class 'MyInteger'|

myInteger\main.cpp|15|error: candidate is: unsigned int& MyInteger::operator[](int)|

Line 15 and Line 20 Give me error messages.
Be careful. Compare the prototype of my definition of the function with your declaration in your class.
Bah, i'm confusing my self, how would I change that, if you could help or show me.
Take the function header from my function definition and use it instead of your function declaration in your class. At least try to compare how I defined the function and how you declared it in the class.
Last edited on
The declaration of the operator inside the class and the definition of it outside the class differ in type. In the class change the declaration of the operator to int operator []( unsigned int index ) const;

If those two definitions don't match, things just don't work out :P
Last edited on
Thank you both!
Topic archived. No new replies allowed.