Please solve it in C Define a class named PositiveInteger to
Please solve it in C++
Define a class named PositiveInteger to represent positive integer. Your class should have the following: 1. A default constructor to initialize the data field to zero. 2. A non default constructor to initialize a specified value. 3. An accessor and a mutator function 4. A getLength( ) function to return the length of the integer. 5. A data field to store the integer value. 6. Overload the subscript operator [] such that the index i will return the digit in position i, with i=0 being the position of least significant digit. The operator should return -1 if the index is out of bound. For example, if num is an object of PositiveInteger and the integer represented is 123, then num[0] will return 3, num[1] will return 2, num[2] will return 1 and num[3] is out of bound will return -1. Negative index value such as num[-1] will also return -1. Use the main method below to test your program: int main() { PositiveInteger num; int intNum, len; cout << \"Please enter an integer: \"; cin >> intNum; num.setInt(intNum); cout << \"getInt returns: \" << num.getInt() << endl; len = num.getLength(); cout<<\"Length of integer is: \"<< len<
Solution
#include <iostream>
 using namespace std;
class PositiveInteger{
    int value;
 public:
    PositiveInteger(){ value= 0; }
    PositiveInteger( int val ){ value = val; }
    int getInt(){ return value; }
    void setInt( int val ){ value = val; }
    int getLength(){
        int length= 0;
        int val = value;
        while( val != 0 ){
            val = val/10;
            length++;
        }
        return length;
    }
    const int operator[](size_t index){
        int length= getLength();
        if( index < 0 || index >= length ){ return -1; }
        index = length - 1- index;
        int val = value;
        for(int i =0; i < index; i++){
            val = val/10;
        }
        return val%10;
    }
 };
int main(){
    PositiveInteger num(123);
    cout << \"Length: \" << num.getLength() << endl;
    cout << num[0] << endl;
    cout << num[1] << endl;
    cout << num[2] << endl;
   return 0;
 }

