InformaticăliceuClasa 11dificil
Supraîncărcarea Operatorilor în C++
Cum să definești comportament personalizat pentru operatori (+, -, *, ==, <<) pe clasele tale.
2 luni în urmă
0 vizualizări
30 minute
Supraîncărcarea Operatorilor în C++
Ce este Supraîncărcarea Operatorilor?
Permite definirea comportamentului operatorilor standard pentru tipuri definite de utilizator.
Exemplu Complet: Clasa Fractie
1#include <iostream> 2using namespace std; 3 4class Fractie { 5private: 6 int numarator; 7 int numitor; 8 9 void simplifica() { 10 int d = __gcd(abs(numarator), abs(numitor)); 11 numarator /= d; 12 numitor /= d; 13 if (numitor < 0) { 14 numarator = -numarator; 15 numitor = -numitor; 16 } 17 } 18 19public: 20 Fractie(int n = 0, int d = 1) : numarator(n), numitor(d) { 21 simplifica(); 22 } 23 24 // Operator + (membru) 25 Fractie operator+(const Fractie& other) const { 26 return Fractie( 27 numarator * other.numitor + other.numarator * numitor, 28 numitor * other.numitor 29 ); 30 } 31 32 // Operator - (membru) 33 Fractie operator-(const Fractie& other) const { 34 return Fractie( 35 numarator * other.numitor - other.numarator * numitor, 36 numitor * other.numitor 37 ); 38 } 39 40 // Operator * (membru) 41 Fractie operator*(const Fractie& other) const { 42 return Fractie(numarator * other.numarator, numitor * other.numitor); 43 } 44 45 // Operator == (membru) 46 bool operator==(const Fractie& other) const { 47 return numarator == other.numarator && numitor == other.numitor; 48 } 49 50 // Operator < (membru) 51 bool operator<(const Fractie& other) const { 52 return numarator * other.numitor < other.numarator * numitor; 53 } 54 55 // Operator << (friend, pentru afișare) 56 friend ostream& operator<<(ostream& os, const Fractie& f) { 57 os << f.numarator; 58 if (f.numitor != 1) os << "/" << f.numitor; 59 return os; 60 } 61 62 // Operator >> (friend, pentru citire) 63 friend istream& operator>>(istream& is, Fractie& f) { 64 char separator; 65 is >> f.numarator >> separator >> f.numitor; 66 f.simplifica(); 67 return is; 68 } 69}; 70 71int main() { 72 Fractie a(1, 2), b(1, 3); 73 74 cout << a << " + " << b << " = " << (a + b) << endl; 75 cout << a << " - " << b << " = " << (a - b) << endl; 76 cout << a << " * " << b << " = " << (a * b) << endl; 77 cout << a << " == " << b << " : " << (a == b ? "true" : "false") << endl; 78 cout << a << " < " << b << " : " << (a < b ? "true" : "false") << endl; 79 80 return 0; 81}
Operatori Care Nu Pot Fi Supraîncărcați
- •
::(scope resolution) - •
.(member access) - •
.*(member pointer access) - •
?:(ternary) - •
sizeof
Reguli Importante
- •Nu poți schimba precedența sau asociativitatea
- •Nu poți crea operatori noi
- •Cel puțin un operand trebuie să fie de tip definit de utilizator
Tutorialul te-a ajutat?
Dacă ai nevoie de ajutor personalizat, găsește un profesor calificat pentru meditații
