Search code examples
c++conversion-operator

how to convert a built-in type to user-defined type


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?


Solution

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