Introduction
C++ में operators का उपयोग calculations और operations के लिए किया जाता है। Operator Overloading के माध्यम से हम इन operators को user-defined types (class objects) के लिए customize कर सकते हैं।
Operators मुख्य रूप से दो प्रकार के होते हैं — Unary और Binary। Unary operators एक operand पर कार्य करते हैं, जबकि Binary operators दो operands पर कार्य करते हैं। इन दोनों प्रकार के operators को class के लिए overload करके हम objects के साथ meaningful operations कर सकते हैं।
Definition
Unary Operators
Unary operators वे operators होते हैं जो केवल एक operand पर कार्य करते हैं।
उदाहरण: ++, --, -
Binary Operators
Binary operators वे operators होते हैं जो दो operands पर कार्य करते हैं।
उदाहरण: +, -, *, /
Unary Operator Overloading
Syntax
returnType operator symbol();
Example (Unary Operator)
#include <iostream>
using namespace std;
class Demo {
public:
int x;
Demo(int v) {
x = v;
}
void operator++() {
x++;
}
};
int main() {
Demo d1(10);
++d1;
cout << "Value: " << d1.x;
return 0;
}
Output:
Value: 11
Binary Operator Overloading
Syntax
returnType operator symbol (ClassName obj);
Example (Binary Operator)
#include <iostream>
using namespace std;
class Number {
public:
int value;
Number(int v) {
value = v;
}
Number operator+(Number n) {
return Number(value + n.value);
}
};
int main() {
Number n1(10), n2(20);
Number n3 = n1 + n2;
cout << "Sum: " << n3.value;
return 0;
}
Output:
Sum: 30
Unary vs Binary Operator में अंतर
| आधार | Unary Operator | Binary Operator |
|---|---|---|
| Operands | एक | दो |
| Example | ++, — | +, -, * |
| Syntax | बिना parameter | parameter के साथ |
| Use | Single value change | Two values combine |
Important Points
- Unary operator → एक object पर काम करता है
- Binary operator → दो objects के बीच काम करता है
- Operator function member या friend दोनों हो सकता है
- Result अक्सर नया object return करता है
Prefix vs Postfix (संक्षेप में)
- Prefix:
++x - Postfix:
x++(extra parameter के साथ define किया जाता है)
निष्कर्ष
Unary और Binary operator overloading के माध्यम से हम objects के साथ विभिन्न operations को define कर सकते हैं। इससे programming अधिक natural और readable बनती है और complex operations को आसानी से implement किया जा सकता है।