-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11_sovraccaricamento.cpp
More file actions
101 lines (73 loc) · 2.49 KB
/
Copy path11_sovraccaricamento.cpp
File metadata and controls
101 lines (73 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <iostream>
using namespace std;
class Point{
private:
int x;
int y;
public:
Point() {}
Point(int _x, int _y) : x(_x), y(_y) {}
const int& get_x() const {return this->x;}
const int& get_y() const {return this->y;}
// METODO FRIEND
// - una funzione esterna alla classe
// - puo' operare sull'oggetto come se fosse un metodo
// - ignora le restrizioni di visibilità
// - possibile rischio per la sicurezza
friend istream& operator>>(istream& in, Point& p);
// CLASSE FRIEND
// friend class ClasseMoltoBella;
// ===== OPERATORI DI CLASSE =====
void operator+=(Point &p){
this->x += p.get_x();
this->y += p.get_y();
}
int operator[](int pos){
if(pos == 0)
return this->x;
else
return this->y;
}
};
// ===== SOVRACCARICAMENTO DI OPERATORE =====
ostream& operator<<(ostream& out, Point& p){
out << "[PUNTO] COORDINATA X: " << p.get_x() << " " << "COORDINATA Y: " << p.get_y() << endl;
return out;
}
istream& operator>>(istream& in, Point& p){
in >> p.x >> p.y;
return in;
}
Point operator+(Point &p1, Point& p2){
Point sum(p1.get_x() + p2.get_x(), p1.get_y() + p2.get_y());
return sum;
}
bool operator==(Point &p1, Point& p2){
return ( (p1.get_x() == p2.get_x()) and (p1.get_y() == p2.get_y()) );
}
bool operator!=(Point &p1, Point& p2){
return not (p1 == p2);
}
int main(){
string str = "Hello World!\n";
Point p(10, 20);
// cout << str; // OK! (forma breve)
// cout << p; // NO! (undefined, senza sovraccaricamento)
// cout.operator<<(str); // ERRORE (operatore di classe)
operator<<(cout, str); // OK! (operatore generico)
cout << p; // OK! (sovraccaricamento definito per la classe Point)
Point p_in;
cout << "Inserire coordinate: "; cin >> p_in;
cout << "Ecco il nuovo punto!" << endl;
cout << p_in;
cout << "Ecco la somma dei punti!" << endl;
Point p_sum = p + p_in;
cout << p_sum;
cout << "I primi due punti sono " << (p == p_in ? "uguali" : "diversi") << endl;
Point p_vect(10, 10);
cout << "Trasliamo..." << endl;
p_sum += p_vect; cout << p_sum;
p_sum.operator+=(p_vect); cout << p_sum;
cout << "WOW! Questo punto descrive una area pari a " << p_sum[0] * p_sum.operator[](1) << endl;
return 0;
}