cpp:friend_methods
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
cpp:friend_methods [2017/04/20 15:23] – gthanos | cpp:friend_methods [2017/04/20 16:09] – gthanos | ||
---|---|---|---|
Line 43: | Line 43: | ||
cout << "area: " << rect.getWidth() * rect.getHeight() << endl; | cout << "area: " << rect.getWidth() * rect.getHeight() << endl; | ||
return 0; | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ====== Φιλικές Κλάσεις ====== | ||
+ | |||
+ | Σε αναλογία με τις φιλικές συναρτήσεις μπορείτε να έχετε και φιλικές κλάσεις που έχουν πρόσβαση στο σύνολο των πεδίων κλάσης. Στο παρακάτω παράδειγμα, | ||
+ | |||
+ | |||
+ | <code cpp Rectangle.cpp> | ||
+ | #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:: | ||
+ | width = w; height = h; | ||
+ | } | ||
+ | |||
+ | void Rectangle:: | ||
+ | void Rectangle:: | ||
+ | int Rectangle:: | ||
+ | int Rectangle:: | ||
+ | </ | ||
+ | |||
+ | <code cpp Cuboid.cpp> | ||
+ | #include < | ||
+ | using namespace std; | ||
+ | |||
+ | #include " | ||
+ | |||
+ | class Cuboid { | ||
+ | Rectangle rect; | ||
+ | int length; | ||
+ | public: | ||
+ | Cuboid(Rectangle r, int l); | ||
+ | int volume(); | ||
+ | }; | ||
+ | |||
+ | Cuboid:: | ||
+ | rect = r; length = l; | ||
+ | } | ||
+ | |||
+ | int Cuboid:: | ||
+ | return rect.width * rect.height * length; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <code cpp CuboidVolume.cpp> | ||
+ | #include < | ||
+ | using namespace std; | ||
+ | |||
+ | #include " | ||
+ | |||
+ | int main() { | ||
+ | Rectangle rectangle(5, | ||
+ | Cuboid cuboid(rectangle, | ||
+ | cout << " | ||
} | } | ||
</ | </ |
cpp/friend_methods.txt · Last modified: 2021/05/18 06:21 (external edit)