📘 Lesson · Lesson 70
Operator Overloading
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 आपको + जैसे operators को अपनी classes के लिए redefine करने देता है।
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; // overloaded + use करता है
cout << c.real << "+" << c.imag << "i"; // 3+7i
return 0;
}Output:
3+7i
3+7i
सारांश
- Objects पर + use करने को class में
operator+(आदि) define करें। - Custom types को built-in types जैसा बनाता है।