dimanche 26 septembre 2021

Overloading an input operator

Currently have a assignment in which I've to create my own BigInt class. The issue I'm having is that I'm not sure how I would be able to overload the input operator the same way I've overloaded =.

My header file is as follows:

#ifndef BIGINT_BIGINT_H
#define BIGINT_BIGINT_H

#include <iostream>

#define BIGINT_SIZE 256

class Bigint {
    public:
        friend std::ostream& operator>> (std::ostream& out, const Bigint& n);

        friend std::ostream& operator<< (std::ostream& out, const Bigint& n);

        // the binary + operator
        Bigint operator+ (const Bigint& n);

        // the binary - operator
        Bigint operator- (const Bigint& n);

        // the binary * operator
        Bigint operator* (const Bigint& n);

        // the binary / operator
        Bigint operator/ (const Bigint& n);

        // the binary = operator:   bigint = bigint
        Bigint& operator= (const Bigint& n);

        // the binary = operator with int:   bigint = int
        Bigint& operator= (int n);

        // the constructor and destructor
        Bigint(int size = BIGINT_SIZE) {digits = size; number = new char[digits]; }

        ~Bigint() { delete[] number; }


    private:
        int  digits;
        char *number;
};


#endif //BIGINT_BIGINT_H

And my cpp file is:

#include "Bigint.h"
#include <iostream>


std::istream& operator>> () {

}


std::ostream& operator<< (std::ostream& out, const Bigint& n) {
    int cntr = 0;

    while ((n.number[cntr] == 0) && (cntr < n.digits-1))
        cntr++;

        while (cntr < n.digits)
            out << (int)n.number[cntr++];

            return out;
}


Bigint& Bigint::operator= (int n) {
    int cntr;

    cntr = digits - 1;
    while (cntr >= 0) {
        number[cntr--] = n % 10;
        n /= 10;
    }

    return *this;
}

Bigint Bigint::operator+ (const Bigint& n) {
    Bigint sum( (digits > n.digits) ? digits : n.digits );
    int nptr, myptr, sumptr;
    char next_n1, next_n2;
    char carry = 0;

    for (sumptr = sum.digits - 1, myptr = digits - 1, nptr = n.digits - 1; sumptr >= 0; sumptr--, myptr--, nptr--) {
        next_n1 = (nptr < 0) ? 0 : n.number[nptr];
        next_n2 = (myptr < 0) ? 0 : number[myptr];
        sum.number[sumptr] = next_n1 + next_n2 + carry;
        if (sum.number[sumptr] > 9) {
            carry = 1;
            sum.number[sumptr] -= 10;
        }
        else{
            carry = 0;
        }
    }

    return sum;
}

I've only actually implemented code to handle the + and = so far.

Aucun commentaire:

Enregistrer un commentaire