My Integer Define a class named MyInteger that stores an integer and has methods
ID: 3534284 • Letter: M
Question
My Integer Define a class named MyInteger that stores an integer and has methods to get and set the integer's value. Then, overload the [] operator so that the index returns the digit in position i, where i = 0 is the least significant digit. If no such digit exists then -1 should be returned. For example, if x is if type MyInteger and it is set to 418, then x[0] should return 8, x [1] should return 1, x [2] should return 4, and x [3] should return -1.Hint: Use / and % to extract a single digit from an integer. You might want to use the pow function to compute 10i. The function is defined in Appendix 4 and requires the cmath library. Submit your source code ( .cpp file )
Explanation / Answer
#include
#include
#include
#define max 50
using namespace std;
class MyInteger
{
public:
MyInteger(int num){this->num=num;}
int getnum(){return num;}
int& operator[](int);
private:
int num;
int a[max];
};
int& MyInteger::operator[](int index)
{
int i;
if(num==0)
{
cout<<"illegal index value ";
index=-1;
return index;
}
if(index==0)
{
a[0]=num;
return a[0];
}
else if(i=index)
{
num/=10;
a[i]=num;
return a[i];
}
}
int main()
{
MyInteger num(418);
cout << num[0] << " ";
cout << num[1] << " ";
cout << num[2] << endl;
cout << num[3] << endl;
cout << num[-1] << endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.