====== Φιλικές συναρτήσεις και φιλικές κλάσεις ======
===== Φιλικές Συναρτήσεις =====
Μία φιλική συνάρτηση της κλάσης είναι μία συνάρτηση που δεν είναι μέλος της κλάσης, αλλά έχει πρόσβαση στα //private// και //protected// μέλη της κλάσης, όπως θα είχε και μία συνάρτηση μέλος. Για να είναι μία συνάρτηση φιλική (//friend//) θα πρέπει να την δηλώσετε ως τέτοια στη δήλωση της κλάσης. Δείτε το παράδειγμα της συνάρτησης //modifyDimensions// η οποία είναι φιλική συνάρτηση της κλάσης //Rectangle//. Παρατηρήστε ότι η συνάρτηση έχει απευθείας πρόσβαση στα //private// πεδία της κλάσης //Rectangle//.
#include
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;
}
#include "Rectangle.hpp"
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;
}
===== Φιλικές Κλάσεις =====
Σε αναλογία με τις φιλικές συναρτήσεις μπορείτε να έχετε και φιλικές κλάσεις που έχουν πρόσβαση στο σύνολο των πεδίων κλάσης. Στο παρακάτω παράδειγμα, η κλάση //Cuboid// είναι φιλική της κλάσης //Rectangle//. Ως φιλική κλάση έχει πρόσβαση στο σύνολο των πεδίων και των μεθόδων της κλάσης //Rectangle//.
#include
using namespace std;
class Rectangle {
friend class Cuboid;
private:
int width, height;
public:
Rectangle(int w, int h);
Rectangle() {}
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; }
#include
using namespace std;
#include "Rectangle.hpp"
class Cuboid {
Rectangle rect;
int length;
public:
Cuboid(Rectangle r, int l);
int volume();
};
Cuboid::Cuboid(Rectangle r, int l) {
rect = r; length = l;
}
int Cuboid::volume() {
return rect.width * rect.height * length;
}
#include
using namespace std;
#include "Cuboid.hpp"
int main() {
Rectangle rectangle(5,6);
Cuboid cuboid(rectangle, 10);
cout << "volume: " << cuboid.volume() << endl;
}
Παρατηρήστε πως η μέθοδος //volume// της κλάσης //Cuboid// υπολογίζει τον όγκο έχοντας απευθείας πρόσβαση στα πεδία της κλάσης //Rectangle//.