Write a program to perform the following statement obj2=obj1+x (int type) and obj2=x+obj1 using operator member function and friend function.
#include <iostream>
using namespace std;
class obj {
private:
int data;
public;
obj(int data) {
this->data = data;
}
int data() { return data; }
}
obj operator+(const obj &a, const int b) {
return obj(a.data() + b);
}
obj operator+(const int a, const obj &b) {
return obj(a + b.data());
}
int main() {
obj a(5);
int b = -3;
obj c = a + b;
cout << c.data() << endl; // 2
obj d = b + a;
cout << d.data() << endl; // 2
return 0;
}
Comments
Leave a comment