Operator Overloading in C++ as int + obj

Azher Iqbal picture Azher Iqbal · Jul 27, 2009 · Viewed 26k times · Source

I have following class:-

class myclass
{
    size_t st;

    myclass(size_t pst)
    {
        st=pst;
    }

    operator int()
    {
        return (int)st;
    }

    int operator+(int intojb)
    {
        return int(st) + intobj; 
    }

};

this works fine as long as I use it like this:-

char* src="This is test string";
int i= myclass(strlen(src)) + 100;

but I am unable to do this:-

int i= 100+ myclass(strlen(src));

Any idea, how can I achieve this??

Answer

Brian R. Bondy picture Brian R. Bondy · Jul 27, 2009

Implement the operator overloading outside of the class:

class Num
{
public:
    Num(int i)
    {
        this->i = i;
    }

    int i;
};

int operator+(int i, const Num& n)
{
    return i + n.i;
}