Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Overloading in C++ as int + obj

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??

like image 637
Azher Iqbal Avatar asked Jul 27 '09 14:07

Azher Iqbal


2 Answers

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;
}
like image 119
Brian R. Bondy Avatar answered Nov 15 '22 19:11

Brian R. Bondy


You have to implement the operator as a non-member function to allow a primitive int on the left hand side.

int operator+( int lhs, const myclass& rhs ) {
    return lhs + (int)rhs;
}
like image 38
Jeff L Avatar answered Nov 15 '22 18:11

Jeff L