Xulosa. Dynamic cast nima uchun kerak ?
Download 48.58 Kb.
|
Dynamic cast
- Bu sahifa navigatsiya:
- The name of the Child is: Banana
printf_s("test2 in B\n");
}}; struct C : B { virtual void test() { printf_s("in C\n"); } void test2() { printf_s("test2 in C\n"); }}; void Globaltest(A& a) { try { C &c = dynamic_cast printf_s("in GlobalTest\n"); } catch(std::bad_cast) { printf_s("Can't cast to C\n"); }} int main() { A *pa = new C; A *pa2 = new B; pa->test(); B * pb = dynamic_cast(pa); if (pb) pb->test2(); C * pc = dynamic_cast if (pc) pc->test2(); C ConStack; Globaltest(ConStack); // muvaffaqiyatsiz bo'ladi, chunki B C haqida hech narsa bilmaydi BonStack; Globaltest(BonStack); } C++ buning uchun dynamic_cast operatoridan foydalanadi. Garchi dinamik casting ota-sinf ko'rsatkichlarini bolalar sinf ko'rsatkichlariga aylantirishdan ko'proq narsani ta'minlaydi, ammo bu dynamic_cast operatorining eng keng tarqalgan qo'llanilishidir. Bu jarayon bolalarni taqsimlash (yoki "pastga tushirish") deb ataladi. Dynamic_cast dan foydalanish static_cast dan foydalanish bilan deyarli bir xil. Mana yuqoridagi misoldagi main() funksiyasi, bu yerda biz dynamic_cast dan Ota-klass koʻrsatgichini Child sinf koʻrsatkichiga aylantirish uchun foydalanamiz: int main() { Parent *p = getObject(true); Child *ch = dynamic_cast std::cout << "The name of the Child is: " << ch->getName() << '\n'; delete p; return 0; } Natija: The name of the Child is: Banana Download 48.58 Kb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling