Download LA PROGRAMMATION POUR... les élèves - imagine

Transcript
10. Constructeurs et Destructeurs
10.3. Cas général
};
p o i n t : : p o i n t ( i n t X , i n t Y) {
x=X ;
y=Y ;
}
...
p o i n t a ( 2 , 3 ) ; / / c o n s t r u i t a v e c p o i n t (X, Y)
point b ;
/ / ERREUR! p o i n t ( ) n ’ e x i s t e p l u s
et il faut alors rajouter un constructeur vide, même s’il ne fait rien :
c l a s s point {
int x , y ;
public :
point ( ) ;
point ( i n t X, i n t Y ) ;
};
point : : point ( ) {
}
p o i n t : : p o i n t ( i n t X , i n t Y) {
x=X ;
y=Y ;
}
...
p o i n t a ( 2 , 3 ) ; / / c o n s t r u i t a v e c p o i n t (X, Y)
point b ;
/ / OK! c o n s t r u i t a v e c p o i n t ( )
10.3.3
Tableaux d’objets
Il n’est pas possible de spécifier globalement quel constructeur est appelé pour les
éléments d’un tableau. C’est toujours le constructeur vide qui est appelé...
point t [ 3 ] ; / / C o n s t r u i t 3 f o i s avec l e c o n s t r u c t e u r v i d e
/ / s u r c h a c u n d e s é l é m e n t s du t a b l e a u
p o i n t ∗ s=new p o i n t [ n ] ; / / Idem , n f o i s
p o i n t ∗ u=new p o i n t ( 1 , 2 ) [ n ] ; / / ERREUR e t HORREUR!
/ / Un e s s a i d e c o n s t r u i r e l e s u [ i ]
/ / avec point ( 1 , 2 ) , qui n ’ e x i s t e pas
Il faudra donc écrire :
p o i n t ∗ u=new p o i n t [ n ] ;
f o r ( i n t i = 0 ; i <n ; i ++)
u[ i ] . set ( 1 , 2 ) ;
ce qui n’est pas vraiment identique car on construit alors les points à vide puis on les
affecte.
Par contre, il est possible d’écrire :
point t [ 3 ] = { point ( 1 , 2 ) , point ( 2 , 3 ) , point ( 3 , 4 ) } ;
ce qui n’est évidemment pas faisable pour un tableau de taille variable.
137