Operator Overloading C++
Adding two objects of same class using + sign.
#include <iostream>
using namespace std;
class a{
int x;
public:
void setX(int);
int getX();
int operator+ (a &obj);
};
int main(){
a obj1, obj2;
obj1.setX(5);
cout << "Obj1.x = " << obj1.getX() << endl;
obj2.setX(10);
cout << "Obj2.x = " << obj2.getX() << endl;
cout <<"\nObj1+Obj2 = " << obj1+obj2 << endl;
return 0;
}
int a::operator+ (a& obj){
return (x + obj.x);
}
void a::setX(int value){
x = value;
}
int a::getX(){
return x;
}
Another Example.
Adding two objects of same class using + sign.
#include <iostream>
using namespace std;
class a{
int x;
public:
void setX(int);
int getX();
int operator+ (a &obj);
};
int main(){
a obj1, obj2;
obj1.setX(5);
cout << "Obj1.x = " << obj1.getX() << endl;
obj2.setX(10);
cout << "Obj2.x = " << obj2.getX() << endl;
cout <<"\nObj1+Obj2 = " << obj1+obj2 << endl;
return 0;
}
int a::operator+ (a& obj){
return (x + obj.x);
}
void a::setX(int value){
x = value;
}
int a::getX(){
return x;
}
Another Example.
No comments:
Post a Comment