|
1 – dars. C++ Dasturlash tilining kelib chiqishi xaqida ma’lumot
|
bet | 85/89 | Sana | 16.11.2023 | Hajmi | 313,45 Kb. | | #100010 |
Bog'liq @AKT Official C haqida o\'zbekcha darslar majmuiPOLIMORF OB'EKT-TELEFON YARATISH
Bir qo’ng’iroqdan ikkinchisiga telefon o’z shaklini o’zgartirishi lozim bo’lsin. Polimorf ob'ekt yaratish uchun avval virtual suzi yordamida virtual usullar yaratiladi:
class phone
{
public:
virtual void dial(char •number) { cout << "Nabor nomera " << number << endl; }
void answer(void) { cout << "Ojidanie otveta" << endl; }
void hangup(void) { cout << "Zvonok vihpolnen - povesit' trubku" << endl; }
void ring(void) { cout << "Zvonok, zvonok, zvonok" << endl; }
phone(char *number) { strcpy(phone::number, number); };
protected:
char number[13];
};
So’ngra dasturda asosiy sinf ob'ektiga ko’rsatkich yaratasiz.
phone *poly_phone;
Shaklni o’zgartirish uchun bu ko’rsatkiyach qiymatiniga hosilaviy sinf ob'ekti adresiga teng qilinadi:
poly_phone = (phone *) &home_phone;
Bu misolda (phone *), tiplarni keltirish operatoridir.
Qo’yidagi POLYMORP.CPP dasturda shu usuldan foydalanilgandir:
#include
#include
class phone
{
public:
virtual void dial(char *number) { cout << "Nabor nomera " << number << endl; }
void answer(void) { cout << "Ojidanie otveta" << endl; }
void hangup(void) { cout << "Zvonok vihpolnen - povesit' trubku" << endl; }
void ring(void) { cout << "Zvonok, zvonok, zvonok" << endl; }
phone(char *number) { strcpy(phone::number, number); };
protected:
char number[13] ;
};
class touch_tone : phone
{
public:
void dial(char * number) { cout << "Pik pik Nabor nomera " << number << endl; }
touch_tone(char *number) : phone(number) { }
};
class pay_phone: phone
{
public:
void dial(char *number) { cout << "Pojaluysta, oplatite " << amount << " tsentov" << endl; cout << "Nabor nomera " << number << endl; }
pay_phone(char *number, int amount) : phone(number) { pay_phone::amount = amount; }
private:
int amount;
};
void main(void)
{
pay_phone city_phone("702-555-1212", 25);
touch_tone home_phone("555-1212");
phone rotary("201-555-1212") ;
// Sdelat' ob'ekt diskovihm telefonom
phone *poly_phone = &rotary;
poly_phone->dial("818-555-1212");
// Zamenit' formu ob'ekta na knopochnihy telefon
poly_phone = (phone *) &home_phone;
poly_phone->dial("303-555-1212");
// Zamenit' formu ob'ekta na platnihy telefon
poly_phone = (phone *) &city_phone;
poly_phone->dial("212-555-1212");
}
Dastur bajarilishi natijasida ekranga kuyidagi ma'lumotlar hosil buladi:
S:\> POLYMORP
Nabor nomera 818-555-1212
Pik pik Nabor nomera 303-555-1212
Pojaluysta, oplatite 25 tsentov
Nabor nomera 212-555-1212
|
| |