Generally the + operator is able to add two integer values or two float values etc but it is not able to add two objects. Suppose we need to add two complex numbers using + operator. We cannot do that directly. for that we need to overload + operator and that can be done using operator overloading as given below.
Class Complex{
public:
int x;
int y;
Complex(int a,int b){
x=a;
y=b;
}
Complex operator+(Complex c);
};
Complex Complex :: operator+(Complex c){
Complex c2;
c2.x=x+c.x;
c2.y=y+c.y;
return c2;
}
void main(){
Complex c1(10,20),c2(-2,4),c3;
c3=c1+c2;
cout<<c3.x
cout<<c3.y
}
Class Complex{
public:
int x;
int y;
Complex(int a,int b){
x=a;
y=b;
}
Complex operator+(Complex c);
};
Complex Complex :: operator+(Complex c){
Complex c2;
c2.x=x+c.x;
c2.y=y+c.y;
return c2;
}
void main(){
Complex c1(10,20),c2(-2,4),c3;
c3=c1+c2;
cout<<c3.x
cout<<c3.y
}
No comments:
Post a Comment