NICKY POMELO Nicky
NICKY POMELO Nicky

Reputation: 1

C++ operator overload?

class CHugeInt
{
private:
    char buf[200];

public:
    void reverse(char *p)
    {
        int i, j, len;

        len = strlen(p), i = 0, j = len - 1;

        while (i <= j)
        {
            swap(p[i], p[j]);

            ++i; 
            --j;
        }
    }

    CHugeInt(int n)
    {
        memset(buf, 0, sizeof(buf));
        sprintf(buf, "%d", n);
        reverse(buf);
    }

    CHugeInt operator + (int n)
    {
        return *this + CHugeInt(n);
    }

    CHugeInt operator + (const CHugeInt &n) const
    {
        int i, k, carry;
        char c1, c2;
        CHugeInt tmp(0);

        carry = 0;

        for (i = 0; i < 210; i++)
        {
            c1 = buf[i];
            c2 = n.buf[i];

            if (c1 == 0 && c2 == 0 && carry == 0)
            {
                break;
            }

            if (c1 == 0)
            {
                c1 = '0';
            }

            if (c2 == 0)
            {
                c2 = '0';
            }

            k = c1 - '0' + c2 - '0' + carry;

            if (k >= 10)
            {
                carry = 1;
                tmp.buf[i] = k - 10 + '0';
            }
            else
            {
                carry = 0;
                tmp.buf[i] = k + '0';
            }
        }

        return tmp;
    }

    friend CHugeInt operator + (int n, const CHugeInt &h)
    {
        return  h + n;
    }
};

int main()
{
    int n;
    char s[210];

    while (cin >> s >> n)
    {
        CHugeInt a(s), b(n);

        cout << n + a << endl;
    }

    return 0;
}

cout << n + a << endl calls friend CHugeInt operator + (int n, const CHugeInt &h).

But why return h + n calls CHugeInt operator + (const CHugeInt &n) const instead of CHugeInt operator + (int n)?

Why it calls CHugeInt operator + (int n) if the const in the parameter of function friend CHugeInt operator + (int n, CHugeInt &h) is removed?

Upvotes: 0

Views: 54

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

The problem is that this operator

CHugeInt operator + (int n)
{
    return *this + CHugeInt(n);
}

is not constant. So it may not be called for a constnat object.

But in this statement

cout << n + a << endl;

there is called the operator

friend CHugeInt operator + (int n, const CHugeInt &h)
{
    return  h + n;
}

where the second parameter has a constant referenced type.

So the compiler uses the conversion constructor

CHugeInt(int n)
{
    memset(buf, 0, sizeof(buf));
    sprintf(buf, "%d", n);
    reverse(buf);
}

and calls the operator

CHugeInt operator + (const CHugeInt &n) const;

Declare the operator like

CHugeInt operator + (int n) const
{
    return *this + CHugeInt(n);
}

Upvotes: 1

Related Questions