səhifə 3/4 tarix 07.01.2024 ölçüsü 15,91 Kb. #210216
1) 13-mavzu(Polimorfizm)
C++ tilida kamida bitta virtual funksiyaga ega bo’lgan sinf abstrakt sinf deyiladi. Abstrakt sinfning asosiy xususiyatidan biri shuki , ushbu turdagi sinfdan obyekt olib bo’lmaydi. Demak sinfni to’la abstractligini ta’minlash uchun quyidagi qonuniyatdan foydalanamiz: class base{ public: virtual vfunc(args....) = 0; ..... } Misol class Base{ public: virtual void display( int i) =0; }; class Derv: public Base{ public: void display(int j) { cout<<"Derv::"< int main(){ Base b; // xato, chunki Base sinf abstrakt Base *ptr = new Derv; ptr->display(10); } Agar nasl olinayotgan class bir necha base classdan nasl olganda hatolik mavjud bo’ladi. Bunday holatlarda nima qilish kerak? Bunday holatlarda virtual base class lar ishlatiladi. protected sin a’zolariga murojaat class base { public: int i; }; class derived1 : public base { public: int j; }; class derived2 : public base { public: int k; }; class derived3 : public derived1, public derived2 { public: int sum;}; int main(){ derived3 ob; ob.i = 10; ob.j = 20; ob.k = 30; ob.sum = ob.i + ob.j + ob.k;} Oldingi misolni hatoligini to’g’irlash class base { public: int i; }; class derived1 : public base { public: int j; }; class derived2 : public base { public: int k; }; class derived3 : public derived1, public derived2 { public: int sum;}; int main(){ derived3 ob; ob.derived1::i = 10; ob.j = 20; ob.k = 30; } Dostları ilə paylaş: