Operator Overloading (+ operator)
C++
Medium
4 views
Problem Description
Overload + operator to add two objects of user-defined class.
This teaches operator overloading concept.
Logic: Define special member function for operator
Official Solution
class Complex {
public:
int real, imag;
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
Complex operator + (const Complex& obj) {
Complex result;
result.real = real + obj.real;
result.imag = imag + obj.imag;
return result;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
void question8_operator_overload() {
Complex c1(3, 4), c2(1, 2);
Complex c3 = c1 + c2;
cout << "Result: ";
c3.display();
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!