User Tools

Site Tools


cpp:friend_methods

Differences

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

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
cpp:friend_methods [2017/04/20 15:23] gthanoscpp:friend_methods [2017/04/20 15:51] gthanos
Line 45: Line 45:
 } }
 </code> </code>
 +
 +====== Φιλικές Κλάσεις ======
 +
 +Σε αναλογία με τις φιλικές συναρτήσεις μπορείτε να έχετε και φιλικές κλάσεις που έχουν πρόσβαση στο σύνολο των πεδίων κλάσης. Στο παρακάτω παράδειγμα, η κλάση //Cuboid// είναι φιλική της κλάσης //Rectangle//. Ως φιλική κλάση έχει πρόσβαση στο σύνολο των πεδίων και των μεθόδων της κλάσης //Rectangle//
 +
 +
 +<code cpp Rectangle.cpp>
 +#include <iostream>
 +using namespace std;
 +
 +class Rectangle {
 +  friend class Cuboid;
 +  private:
 +    int width, height;
 +  public:
 +    Rectangle(int w, int h);
 +    void setWidth(int w);
 +    void setHeight(int h);
 +    int getWidth();
 +    int getHeight();
 +};
 +
 +Rectangle::Rectangle(int w, int h) {
 +  width = w; height = h;
 +}
 +
 +void Rectangle::setWidth(int w) { width = w; }
 +void Rectangle::setHeight(int h) { height = h; }
 +int Rectangle::getWidth() { return width; }
 +int Rectangle::getHeight() { return height; }
 +</code>
 +
 +<code cpp Cuboid.cpp>
 +#include <iostream>
 +using namespace std;
 +
 +#include "Rectangle.cpp"
 +
 +class Cuboid {
 +  Rectangle r;
 +  int length;
 +public:
 +  void modifyDimensions(int dw, int dh, int dl) {
 +    r.width += dw;
 +    r.height += dh;
 +    length += dl;
 +  }
 +}
 +<code>
cpp/friend_methods.txt · Last modified: 2021/05/18 06:21 (external edit)