Overload Operator + to implement below operations:
- Obj1 + Obj2
- 12 + Obj2
- Obj1 + 10
Overload Operator - to implement below operations:
- Obj1 - Obj2
- 12 - Obj2
- Obj1 - 10
Mainly looking to overload: Obj1 - 10, 12 - Obj2, 12 + Obj2, Obj1 + 10 cases I wanted to overload operator + and - such that above all operation are handled. How to handle these operation/cases? Here I am facing problem with 2nd case. I am thinking to write only one function each for + and - to handle these case.
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator + (Complex const &obj) {
Complex res;
res.real = this->real + obj.real;
res.imag = this->imag + obj.imag;
return res;
}
Complex operator + (int i) {
Complex res;
res.real = this->real + i;
res.imag = this->imag ;
return res;
}
Complex operator - (Complex const &obj) {
Complex res;
res.real = this->real - obj.real;
res.imag = this->imag - obj.imag;
return res;
}
Complex operator - (int i) {
Complex res;
res.real = this->real - i;
res.imag = this->imag ;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex Obj1(10, 5), Obj2(2, 4);
Complex Obj3 = Obj1 + Obj2;
Complex Obj4 = 10 + Obj3;
Complex Obj5 = Obj4 + 15;
cout<<" + operation:"<<endl;
Obj3.print();
Obj4.print();
Obj5.print();
Complex Obj6 = Obj1 - Obj2;
Complex Obj7 = 10 - Obj3;
Complex Obj8 = Obj4 - 15;
cout<<" - operation:"<<endl;
Obj6.print();
Obj7.print();
Obj8.print();
}
Expected Output:
+ operation:
12 + i9
22 + i9
37 + i9
- operation:
8 + i
2 + i9
7 + i9
Getting below error:
error: no match for 'operator+' (operand types are 'int' and 'Complex')
Complex Obj4 = 10 + Obj3;