1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| struct A{
int a;
A():a(0){}
virtual ~A(){} // dynamic_cast nécessite que la classe soit polymorphe
};
struct B : public A{
int b;
B():b(1){}
};
struct C : public A{
int c;
C():c(2){}
};
int main()
{
A a;
B b;
C c;
A*pa;
B*pb;
C*pc;
pa = &a;
pb = static_cast<B*>(pa);// compil OK, exécution indéterminée (probablement pb!=NULL et membre==n'importe quoi)
pc = dynamic_cast<C*>(pa);// à l'exécution pc == NULL;
pa = &b;
pb = static_cast<B*>(pa);// compil OK, exécution OK
pc = dynamic_cast<C*>(pa);// à l'exécution pc == NULL;
pa = &c;
pb = static_cast<B*>(pa);// compil OK, exécution indéterminée (probablement pb!=NULL et membre==n'importe quoi)
pc = dynamic_cast<C*>(pa);// pc!=NULL
return 0;
} |
Partager