User Tools

Site Tools


cpp:friend_methods

This is an old revision of the document!


Φιλικές Συναρτήσεις

Μία φιλική συνάρτηση της κλάσης είναι μία συνάρτηση που δεν είναι μέλος της κλάσης, αλλά έχει πρόσβαση στα private και protected μέλη της κλάσης, όπως θα είχε και μία συνάρτηση μέλος. Για να είναι μία συνάρτηση φιλική (friend) θα πρέπει να την δηλώσετε ως τέτοια στη δήλωση της κλάσης. Δείτε το παράδειγμα της συνάρτησης modifyDimensions η οποία είναι φίλια συνάρτηση της κλάσης Rectangle. Παρατηρήστε ότι η συνάρτηση έχει απευθείας πρόσβαση στα private πεδία της κλάσης Rectangle.

Rectangle.cpp
#include <iostream>
using namespace std;
 
class Rectangle {
  private:
    int width, height;
  public:
    Rectangle(int w, int h);
    void setWidth(int w);
    void setHeight(int h);
    int getWidth();
    int getHeight();
    friend void modifyDimensions(Rectangle r, int dw, int dh);
};
 
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; }
 
void modifyDimensions(Rectangle r, int dw, int dh) {
  r.width += dw;
  r.height += dh;
}
RectangleUsage.cpp
#include "Rectangle.cpp"
 
int main () {
  Rectangle rect(5,6);  
  cout << "area: " << rect.getWidth() * rect.getHeight() << endl;
  modifyDimensions(rect, 1, 1);
  cout << "area: " << rect.getWidth() * rect.getHeight() << endl;
  return 0;
}
cpp/friend_methods.1492701814.txt.gz · Last modified: 2017/04/20 14:23 (external edit)