This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision Next revision Both sides next revision | ||
|
cpp:polymorphism [2017/04/25 12:21] gthanos |
cpp:polymorphism [2017/04/25 12:55] gthanos |
||
|---|---|---|---|
| Line 5: | Line 5: | ||
| <code cpp ShapeUsage.cpp> | <code cpp ShapeUsage.cpp> | ||
| #include " | #include " | ||
| - | #include " | ||
| int main() { | int main() { | ||
| Line 54: | Line 53: | ||
| Rectangle reference area: 200 | Rectangle reference area: 200 | ||
| Rectangle pointer area: 200 | Rectangle pointer area: 200 | ||
| + | </ | ||
| + | |||
| + | ====== Pure Virtual συναρτήσεις και abstract κλάσεις ====== | ||
| + | |||
| + | Εκτός από τις //virtual// μεθόδους που είδαμε προηγούμενα μπορούμε να έχουμε και //pure virtual// μεθόδους. Οι μέθοδοι που χαρακτηρίζονται //pure virtual// όταν ορίζονται σε μία κλάση, δηλώνεται μόνο το // | ||
| + | <code cpp> | ||
| + | virtual <return type> < | ||
| + | </ | ||
| + | |||
| + | Η κλάση που περιέχει μία ή περισσότερες //pure virtual// συναρτήσεις είναι // | ||
| + | |||
| + | Για παράδειγμα, | ||
| + | |||
| + | <code cpp Shape.cpp> | ||
| + | #include < | ||
| + | #include < | ||
| + | using namespace std; | ||
| + | |||
| + | #ifndef __SHAPE2D__ | ||
| + | #define __SHAPE2D__ | ||
| + | |||
| + | class Shape2D { | ||
| + | unsigned int color; | ||
| + | protected: | ||
| + | unsigned char borderWidth; | ||
| + | public: | ||
| + | Shape2D(unsigned int c, unsigned char bw); | ||
| + | Shape2D(unsigned char red, unsigned char blue, unsigned char green, unsigned char bw); | ||
| + | void setColor(unsigned int c); | ||
| + | void setColor(unsigned char red, unsigned char blue, unsigned char green); | ||
| + | unsigned int getColor(); | ||
| + | unsigned char getBorderWidth(); | ||
| + | void setBorderWidth(unsigned char bw); | ||
| + | virtual unsigned int getArea() = 0; | ||
| + | }; | ||
| + | |||
| + | void Shape2D:: | ||
| + | void Shape2D:: | ||
| + | color = red; | ||
| + | color <<= 8; | ||
| + | color |= blue; | ||
| + | color <<= 8; | ||
| + | color |= green; | ||
| + | } | ||
| + | |||
| + | unsigned int Shape2D:: | ||
| + | Shape2D:: | ||
| + | Shape2D:: | ||
| + | unsigned char Shape2D:: | ||
| + | void Shape2D:: | ||
| + | #endif | ||
| + | </ | ||
| + | |||
| + | Αντίστοιχα, | ||
| + | <code cpp> | ||
| + | unsigned int Rectangle:: | ||
| + | return width * height; | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Επειδή η κλάση //Shape2D// είναι πλέον // | ||
| + | <code cpp ShapeUsage.cpp> | ||
| + | #include " | ||
| + | |||
| + | int main() { | ||
| + | Rectangle rectangle(0xffffff, | ||
| + | Shape2D & | ||
| + | |||
| + | cout << " | ||
| + | cout << " | ||
| + | cout << " | ||
| + | } | ||
| </ | </ | ||