|
1- лаборатория ишиBog'liq 1.1 amaliyconst_cast
(expr)
static_cast
operatori.
Static_cast
Operatori polimorf bo‘lmagan tipdagi ko‘rsatkichlarni almashtirish uchun
foydalaniladi. Har qanday tipni almashtirish uchun foydalanish mumkin. Biroq, dastur
bajarilgan vaqtda hech qanday tekshirish amalga oshirilmaydi.
Static_cast operatori quyidagi umumiy yozuv formatiga ega:
static_cast (expr)
dynamic_cast operatoridan foydalanish.
#include "stdafx.h"
#include #include using namespace std; class Base { public:
virtual void f() { cout << " Base sinfi orqali.\n"; }
// . . .
}; class myClass : public Base { public: void f() { cout << "myClass sinfi
orqali.\n"; } }; int main(){ Base *bp, b_ob; myClass *dp, d_ob; dp =
dynamic_cast (&d_ob); if(dp) {
cout << " tipni almashtirish" <<" (myClass* => myClass *) bajarildi. "; dp->f();
} else cout <<"Xatolik\n"; cout << endl; bp = dynamic_cast (&d_ob); if(bp)
{
cout << " tipni almashtirish " <<"(myClass*
=> Base *) bajarildi. "; bp->f();
} else cout << "Xatolik\n"; cout << endl; bp = dynamic_cast (&b_ob); if(bp)
{
cout << " tipni almashtirish " <<"(Base* =>
Base *) bajarildi. "; bp->f();
} else cout << "Xatolik\n"; cout << endl;
dp = dynamic_cast (&b_ob); if(dp) cout <<"Xatolik\n";
else
cout <<" tipni almashtirish "<<"(Base*=> myClass*) bajarilmadi.\n"; cout << endl;
bp = &d_ob; // bp myClass ob'eyktiga koʻrsatkich
dp = dynamic_cast (bp); if(dp) {
cout << " bp ni myClass tipiga almashtirish
bajarildi. "; dp->f();
} else cout << "Xatolik\n"; cout << endl; bp = &b_ob; // br Base ob'eyktiga koʻrsatkich
dp = dynamic_cast (bp); if(dp) cout << "Xatolik"; else cout <<" bp
myClass tipiga almashtirish bajarilmadi.\n"; cout << endl;
dp = &d_ob; // dp myClass ob'eyktiga koʻrsatkich bp = dynamic_cast (dp);
if(bp) {
cout <<" dp ni myClass tipiga almashtirish
bajarildi. "; bp->f(); } else cout <<"Xatolik\n"; system("pause"); return 0;
}
Dasturnatijasi: output tipni almashtirish (myClass* => myClass *) bajarildi. myClass
sinfi orqali. tipni almashtirish (myClass* => Base *) bajarildi.
myClass sinfi orqali.
tipni almashtirish (Base* => Base *) bajarildi.
Base sinfi orqali.
tipni almashtirish (Base*=> myClass*) bajarilmadi. bp ni myClass tipiga almashtirish
bajarildi.
myClass sinfi orqali. bp myClass tipiga almashtirish bajarilmadi. dp ni myClass tipiga
almashtirish bajarildi. myClass sinfi orqali.
|
| |