cpp:constructors_destructors

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision Both sides next revision
cpp:constructors_destructors [2020/04/08 09:05]
gthanos
cpp:constructors_destructors [2020/04/08 09:11]
gthanos
Line 132: Line 132:
 Rectangle::Rectangle(int w, int h) : width(w), height(h) {} Rectangle::Rectangle(int w, int h) : width(w), height(h) {}
 </code> </code>
 +
 +Τελικά η κλάση Rectangle μπορεί να γραφεί ως εξής:
 +
 +<code cpp Rectangle.hpp>
 +#include <iostream>
 +#include <cstdlib>
 +#include <ctime>
 +using namespace std;
 +
 +class Rectangle {
 +  private:
 +    int width, height;
 +  public:
 +    Rectangle(int w, int h);
 +    Rectangle(int s);
 +    Rectangle();
 +    void setWidth(int w);
 +    void setHeight(int h);
 +    int getWidth() const;
 +    int getHeight() const;
 +};
 +
 +Rectangle::Rectangle(int w, int h) : width(w), height(h) {
 +}
 +
 +Rectangle::Rectangle(int s) : width(s), height(s) {
 +}
 +
 +Rectangle::Rectangle() {
 +  srand(time(NULL));
 +  width = rand() % 10 + 1; height = rand() % 10 + 1;
 +}
 +
 +void Rectangle::setWidth(int w) { width = w; }
 +void Rectangle::setHeight(int h) { height = h; }
 +int Rectangle::getWidth() const { return width; }
 +int Rectangle::getHeight() const { return height; }
 +</code>
 +
 +
 +
  
 Ο παραπάνω τρόπος αρχικοποίησης μπορεί να επεκταθεί και να χρησιμοποιηθεί για την κλήση κατασκευαστών των πεδίων της κλάσης, όταν αυτά είναι αναφορικού τύπου. Για παράδειγμα, δείτε παρακάτω την κλάση //Cuboid// η οποία διαθέτει ένα πεδίο της κλάσης //Rectangle// Ο παραπάνω τρόπος αρχικοποίησης μπορεί να επεκταθεί και να χρησιμοποιηθεί για την κλήση κατασκευαστών των πεδίων της κλάσης, όταν αυτά είναι αναφορικού τύπου. Για παράδειγμα, δείτε παρακάτω την κλάση //Cuboid// η οποία διαθέτει ένα πεδίο της κλάσης //Rectangle//
cpp/constructors_destructors.txt · Last modified: 2020/04/08 09:33 (external edit)