This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | Next revision Both sides next revision | ||
|
cpp:destructors [2021/05/17 06:36] |
cpp:destructors [2021/05/17 07:35] gthanos |
||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ===== Καταστροφείς της κλάσης ===== | ||
| + | |||
| + | Εκτός από τον κατασκευαστή μίας κλάσης, | ||
| + | |||
| + | Στο παρακάτω παράδειγμα βλέπετε την κλάση // | ||
| + | |||
| + | <code cpp Rectangle.hpp> | ||
| + | #include < | ||
| + | #include < | ||
| + | using namespace std; | ||
| + | |||
| + | class Rectangle { | ||
| + | private: | ||
| + | int* width; | ||
| + | int* height; | ||
| + | public: | ||
| + | Rectangle(int w, int h); | ||
| + | ~Rectangle(); | ||
| + | void setWidth(int w); | ||
| + | void setHeight(int h); | ||
| + | int getWidth(); | ||
| + | int getHeight(); | ||
| + | }; | ||
| + | </ | ||
| + | |||
| + | <code cpp Rectangle.cpp> | ||
| + | #include " | ||
| + | |||
| + | Rectangle:: | ||
| + | width = new (nothrow) int; | ||
| + | height = new (nothrow) int; | ||
| + | if(width == NULL || height == NULL) { | ||
| + | cerr << " | ||
| + | exit(-1); | ||
| + | } | ||
| + | *width = w; *height = h; | ||
| + | cout << " | ||
| + | } | ||
| + | |||
| + | Rectangle:: | ||
| + | cout << " | ||
| + | delete width; | ||
| + | delete height; | ||
| + | } | ||
| + | |||
| + | void Rectangle:: | ||
| + | void Rectangle:: | ||
| + | int Rectangle:: | ||
| + | int Rectangle:: | ||
| + | </ | ||
| + | |||
| + | <code cpp RectangleUsage.cpp> | ||
| + | int main () { | ||
| + | Rectangle rect(5,6); | ||
| + | cout << "area: " << rect.getWidth() * rect.getHeight() << endl; | ||
| + | return 0; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Στο παραπάνω παράδειγμα, | ||
| + | |||
| + | |||