Question

I have a class called BigInteger which supports big integer operation. I want to implement mixture operation between BigInteger and built-in type 'int'. In other word, I want to support following statements

BigInteger a(10);
a + 10;
10 + a;

I know overloaded function can deal with it

BigInteger operator +(const BigInteger&, const int&);
BigInteger operator +(const int&, const BigInteger&);

Besides, I know a conversion operator can only deal with it ,

operator int();

But the above function support convert BigInteger to int which will lose precision. I am looking for some methods which will be simpler than overloaded function and keep precision.

Thanks, everyone.

I try it,

#include <iostream>
using namespace std;

class BigInteger
{
public:
    BigInteger(const int& i)
    {
        cout << "construct: " << i << endl;
        val = i;
    }

//    BigInteger operator +(const BigInteger& tmp) const
//    {
//        return BigInteger(val + tmp.val);
//    }

    friend ostream& operator <<(ostream& os, const BigInteger& bi)
    {
        os << bi.val << endl;
        return os;
    }

    int val;
};

BigInteger operator +(const BigInteger& a, const BigInteger& b)
{
    return BigInteger(a.val + b.val);
}

int main(int argc, const char *argv[])
{
    BigInteger a(12);
    cout << (a + 123) << endl;
    cout << (1231 + a) << endl;

    return 0;
}

why can't I use member function? How it works?

Was it helpful?

Solution 2

So, make a constructor BigInteger(int), and define an BigInteger operator(const BigInteger &lhs, const BigInteger &rhs).

OTHER TIPS

You need to add constructor that will take value of BigInteger from int

BigInteger (const int& value)

You should implement overloads for BigInteger operator+(BigInteger const&, int); As Herb Sutter and Andrei Alexandrescu wrote in C++ Coding Standarts (Item 29) you should "Consider overloading to avoid implicit type conversation". Your BigInteger might use operator new for construction wich can be avoided in this particular case. Additionally you should implement the binary operation in terms of unary operation:

class BigInteger {
  // ..
public:
    BigInteger& operator+=(int); // this operation can reuse BigIntegers buffer
  // ..
}

BigInteger operator+(BigInteger lhs, int rhs)
{
  return lhs+=rhs;
}

BigInteger operator+(int lhs, BigInteger rhs)
{
   return rhs+=lhs;
}

Make sure that you are only ever converting from int to BigInteger, never the reverse. Or, throw an exception if the reverse conversion would lead to an overflow.

define the constructor BigInteger(int) and overload the operator BigInteger operator+(const BigInteger &left, const BigInteger &right).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top