Search code examples
c++classarbitrary-precision

Creating custom data type c++


I'm attempting to create a Number class that mimics an arbitrary precision data type.

I want to be able to execute the following operations:

Number a, b;
cin >> a >> b;
cout << "The sum of " << a << " and " << b << " is " 
<< a+b << endl;

Currently I have:

class Number {
   public:
        Number & operator = (const Number & N);
        bool operator == (const Number & N) const;
        bool operator != (const Number & N) const;
        bool operator < (const Number & N) const;
        bool operator > (const Number & N) const;
        bool operator <= (const Number & N) const;
        bool operator >= (const Number & N) const;
        Number operator += (const Number & N);
        Number operator + (const Number & N) const;
        Number operator *= (const Number & N);
        Number operator * (const Number & N) const;
        friend ostream & operator << (ostream & output, const Number & N);
        friend istream & operator >> (istream & input, Number & N);
};

How would I be able to set the Number Class to a particular value?

Number foo = 5;

Solution

  • For that line, you need a constructor. Here is one example:

    class Number {
    public:
        Number(int I = 0);
    ...
    };
    

    If, for example, your numbers are stored as a sequence of digits in a std::vector<int> called m_digits, then the definition of your constructor might look like this:

    Number::Number(int I) : m_digits(1, I)
    {
    }