Define operator a custom class: =, +
#include <iostream>
using namespace std;
class myClass {
public:
int count;
myClass operator=(myClass obj);
friend myClass operator+(myClass ob, int i);
friend myClass operator+(int i, myClass ob);
};
myClass myClass::operator=(myClass obj)
{
count = obj.count;
return *this;
}
// ob + int.
myClass operator+(myClass ob, int i)
{
myClass temp;
temp.count = ob.count + i;
return temp;
}
// int + ob.
myClass operator+(int i, myClass ob)
{
myClass temp;
temp.count = ob.count + i;
return temp;
}
int main()
{
myClass myObject;
myObject.count = 10;
cout << myObject.count << " ";
myObject = 10 + myObject;
cout << myObject.count << " ";
myObject = myObject + 12;
cout << myObject.count;
return 0;
}
Related examples in the same category