Полиморфизм.pptx
- Количество слайдов: 15
Полиморфизм
Указатели на базовые классы • Указатели на базовые классы совместимы с указателями на производные классы
// pointers to base class #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } }; class CRectangle: public CPolygon { public: int area () { return (width * height); } };
class CTriangle: public CPolygon { public: int area () { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly 1 = ▭ CPolygon * ppoly 2 = &trgl; ppoly 1 ->set_values (4, 5); ppoly 2 ->set_values (4, 5); cout << rect. area() << endl; //нужно напрямую обращаться к самому объекту cout << trgl. area() << endl; return 0; }
Виртуальные аргументы • Аргумент класса, который может быть переопределен в производном класса называется виртуальным аргументом. Для объявления виртуального аргумента используется ключевое слово virtual
• // virtual members • #include <iostream> • using namespace std; • class CPolygon { • protected: • int width, height; • public: • void set_values (int a, int b) • { width=a; height=b; } • virtual int area () • { return (0); } • };
• class CRectangle: public CPolygon { • public: • int area () • { return (width * height); } • }; • class CTriangle: public CPolygon { • public: • int area () • { return (width * height / 2); } • };
• int main () { • CRectangle rect; • CTriangle trgl; • CPolygon poly; • CPolygon * ppoly 1 = ▭ • CPolygon * ppoly 2 = &trgl; • CPolygon * ppoly 3 = &poly; • ppoly 1 ->set_values (4, 5); • ppoly 2 ->set_values (4, 5); • ppoly 3 ->set_values (4, 5); • cout << ppoly 1 ->area() << endl; • cout << ppoly 2 ->area() << endl; • cout << ppoly 3 ->area() << endl; • return 0; • }
• Класс, который наследует виртуальные методы называется полиморфным классом.
Абстрактные классы • class CPolygon { • protected: • int width, height; • public: • void set_values (int a, int b) • { width=a; height=b; } • virtual int area () =0; //простая виртуальная функция • };
• Абстрактный класс не может иметь объектов. Но объявление указателя абстрактного класса возможно CPolygon poly; - не корректно, так как означает объявления объекта класса CPolygon * ppoly 1; CPolygon * ppoly 2; - эти выражения абсолютно правильные, так как здесь не объявляются объекты, а создаются указатели на объекты
// pure virtual members can be called // from the abstract base class #include <iostream> using namespace std; class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << this->area() << endl; } };
class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } }; int main () { CRectangle rect; CTriangle trgl; CPolygon * ppoly 1 = ▭ CPolygon * ppoly 2 = &trgl; ppoly 1 ->set_values (4, 5); ppoly 2 ->set_values (4, 5); ppoly 1 ->printarea(); ppoly 2 ->printarea(); return 0;
• • • Динамическое создание объектов класса // dynamic allocation and polymorphism #include <iostream> using namespace std; • • • class CPolygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0; void printarea (void) { cout << this->area() << endl; } }; • • • class CRectangle: public CPolygon { public: int area (void) { return (width * height); } }; • • • class CTriangle: public CPolygon { public: int area (void) { return (width * height / 2); } };
int main () { CPolygon * ppoly 1 = new CRectangle; CPolygon * ppoly 2 = new CTriangle; ppoly 1 ->set_values (4, 5); ppoly 2 ->set_values (4, 5); ppoly 1 ->printarea(); ppoly 2 ->printarea(); delete ppoly 1; delete ppoly 2; return 0; }
Полиморфизм.pptx