This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
|
cpp:operator_overloading [2017/04/26 14:00] gthanos created |
cpp:operator_overloading [2021/05/24 06:28] |
||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== Υπερφόρτωση τελεστών ====== | ||
| - | Η C++ επιτρέπει την // | ||
| - | |||
| - | <code cpp Time.cpp> | ||
| - | class Time { | ||
| - | int minutes; | ||
| - | int hours; | ||
| - | public: | ||
| - | Time(int hours, int minutes) { | ||
| - | if(hours >= 0) | ||
| - | this-> | ||
| - | else | ||
| - | this-> | ||
| - | if(minutes >= 0) | ||
| - | this-> | ||
| - | else | ||
| - | this-> | ||
| - | } | ||
| - | int getMinutes() { return minutes; } | ||
| - | int getHours() { return hours; } | ||
| - | }; | ||
| - | |||
| - | int main() { | ||
| - | Time t1(10,30), t2(12, 50); | ||
| - | Time t3 = t1 + t2; | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | Προς το παρόν αυτό που θα συμβεί είναι ότι ο παραπάνω κώδικας δεν μεταγλωττίζεται καθώς δεν ορίζεται κάποια συμπεριφορά για τον τελεστή '' | ||
| - | |||
| - | <code cpp Time.cpp> | ||
| - | |||
| - | #include < | ||
| - | class Time { | ||
| - | int minutes; | ||
| - | int hours; | ||
| - | public: | ||
| - | Time(int hours, int minutes) { | ||
| - | if(hours >= 0) | ||
| - | this-> | ||
| - | else | ||
| - | this-> | ||
| - | if(minutes >= 0) | ||
| - | this-> | ||
| - | else | ||
| - | this-> | ||
| - | } | ||
| - | Time operator+(const Time &t) { | ||
| - | Time f(hours, minutes); | ||
| - | f.minutes += t.minutes; | ||
| - | if(f.minutes> | ||
| - | f.minutes -= 60; | ||
| - | f.hours++; | ||
| - | f.hours += t.hours; | ||
| - | if(f.hours > 24) | ||
| - | f.hours -= 24; | ||
| - | return f; | ||
| - | } | ||
| - | int getMinutes() { return minutes; } | ||
| - | int getHours() { return hours; } | ||
| - | }; | ||
| - | |||
| - | int main() { | ||
| - | Time t1(10,30), t2(12, 50); | ||
| - | Time t3 = t1 + t2; | ||
| - | std::cout << "t3: " << t3.getHours() <<" | ||
| - | } | ||
| - | </ | ||