Answer to Question #248858 in C++ for gyan

Question #248858

Write a program to perform the following statement obj2=obj1+x (int type) and obj2=x+obj1 using operator member function and friend function.


1
Expert's answer
2021-10-11T02:56:15-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS