Making operations with a class as an operand possible in C++

I'm fairly familiar with operator overloading, however I am wondering how do we implement something like this:

myClass myclassobj;
int x;
x = 5;
x = x + myclassobj

There is no way to overload the + operator for the int class, so something should be done from myClass, but how would we do that? I am probably using the wrong keywords, but searching through SO didn't lead to anithing. Apologies if I did something wrong, this is my first post here.

Edit - My class is a custom vector class, so simply converting it to given type won't work.

Answers


Define an overloaded operator with the signature int operator+(int, myClass).


You are right.

There is no way to overload the + operator for the int class, so something should be done from myClass

Your question:

but how would we do that?

My answer:

You should use user defined type conversion. It may work with a conversion operator.

#include <iostream>

class myClass
{
    int i;
public:
    myClass(int i=0) : i(i) {  }
    operator int(){ // A conversion from myClass to int may solve your problem.
        return i;
    }
};

int main()
{
    myClass myclassobj(99);
    int x=7;
    x = 5;
    x = x + myclassobj;

    std::cout<<x<<std::endl;

    return 0;
}

Brian gave a good answer also, but it works only if the overloaded operator does not need protected or private members from the second argument or if overloaded operator declared as friend of myClass.


Need Your Help

How to quote column names with Zend_Db?

php mysql zend-framework zend-db-table

I am using key as a column name in a MySQL table.

PHP GET question - calling from a POST call

php search post get google-analytics

I have a quick question i hope you guys can answer, i've got a search system that uses POST to do searches, now i want to track queries using Google Analytics but it requires using GET url paramete...