Xulosa. Dynamic cast nima uchun kerak ?


Download 48.58 Kb.
bet6/7
Sana28.12.2022
Hajmi48.58 Kb.
#1011767
1   2   3   4   5   6   7
Bog'liq
Dynamic cast

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(a);
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(pa2);
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(p); // Ota-klass ko'rsatgichini Child sinf ko'rsatkichiga aylantirish uchun dynamic_cast dan foydalaning
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:
1   2   3   4   5   6   7




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling