Hi I am trying to do operator overloading for +(addition) operator to add my user defined datatype objects .
Following is the code for that.
#include <iostream>
using namespace std;
class complex {
int i;
double f;
public:
complex(int ii=0,double ff=0){
i = ii;
f = ff;
}
complex operator+(complex object) {
complex result;
result.i = this->i + object.i;
result.f = this->f + object.f;
return result;
}
void display() {
cout << i <<"\t"<< f;
cout << endl;
}
};
int main(){
complex obj1(1,1.1),obj2(2,2.2),obj3;
int i(5);
obj3 = obj1 + obj2;
obj3.display();
obj3 = obj3 + i;
obj3.display();
obj3 = i + obj3;//generates me compiler error
obj3.display();
return 0;
}
I have learnt that when I do obj1 + obj2,it is expanded by the compiler as obj1.operator+(obj2);
So that part of code works fine.
But when I do add an int and complex ,I think it get expanded as i.operator(obj1).
So it gives me compiler errors.
Should I define operator+ function in int class or how to solve this?
Please suggest,
Thank you,
You will have to provide an overloaded version of
+which takesintand classcomplexobject as input parameters. This function should be a non member function.Note that additionally, if you want to access
protectedorprivatemembers inside this overloaded function then it will have to be madefriendof yourcomplexclass.This is a peculiar example of the strength of free functions used for operator overloading as against member function operator overloads.