📘 Lesson · Lesson 70
Operator Overloading
What is Operator Overloading?
💡 Note
Operator overloading lets you redefine operators like + for your own classes.
Example
C++
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r, int i) : real(r), imag(i) {}
Complex operator + (Complex c) {
return Complex(real + c.real, imag + c.imag);
}
};
int main() {
Complex a(2,3), b(1,4);
Complex c = a + b; // uses overloaded +
cout << c.real << "+" << c.imag << "i"; // 3+7i
return 0;
}Output:
3+7i
3+7i
Summary
- Define
operator+(etc.) in your class to use + on objects. - Makes custom types behave like built-in types.
Operator Overloading क्या है?
💡 Note
Operator overloading lets you redefine operators like + for your own classes.
Example
C++
#include <iostream>
using namespace std;
class Complex {
public:
int real, imag;
Complex(int r, int i) : real(r), imag(i) {}
Complex operator + (Complex c) {
return Complex(real + c.real, imag + c.imag);
}
};
int main() {
Complex a(2,3), b(1,4);
Complex c = a + b; // uses overloaded +
cout << c.real << "+" << c.imag << "i"; // 3+7i
return 0;
}Output:
3+7i
3+7i
सारांश
- Define
operator+(etc.) in your class to use + on objects. - Makes custom types behave like built-in types.
💻 लाइव कोड एडिटर
इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.