Vous êtes sur la page 1sur 2

11.

Les conversions de type

11.1 Par les constructeurs : constructeur de conversion

Class Complex
{ ...
friend Complex operator+ (Complex, Complex );
public :
Complex( int a, int b = 0);
...
};

Complex x( 0, 0), y( -1, 2);


Complex z = 5 ; // z = Complex( 5, 0 );
x=y+2 // x = operator+ ( y, Complex( 2, 0 ) )

Si on a un constructeur à un argument, il effectue automatiquement une conversion de


type.
Le constructeur à un argument est appelé un constructeur de conversion.

11.2 Par un opérateur : opérateur de conversion.

sous la forme X :: operator T () => conversion du type X vers le type T.

Class BigInt
{
char text[ 50];
public :
BigInt (int i ) ; // constructeur (de conversion)
void operator= ( int i ); // affectation
operator int () ; // operateur de conversion
};

BigInt big = 123; // construction : big = BigInt( 123 ) big.text  "123"


big = 5; // affectation : operator = big.text  "5"
int i ;
i = big; // conv. de type : i = big.operator int( ) i  (entier( big.text )

Autre exemple :

Point p( 1, 2 );
Complex z;

z=p; // z = p.operator Complex()


Class Point
{
int abscisse, ordonnee ;
public :
Point( int a, int o ) { abscisse = a; ordonnee = o; }
operator Complex () { return Complex (abscisse, ordonnee ) ; }
};

Complex
{
float re, im ;
public :
Complex( float xx = 0, float yy = 0 ) ;
Complex operator + ( Complex ) }
};

Autre exemple : soit une classe String


On peut y définir un opérator const char *
cet opérator sera utilisé chaque fois qu’une fonction a besoin d’un const char * en
paramètre et qu’on lui passera un objet du type String

class String
{
char *str;
public :
String( const char * ) ;
operator const char * () { return str ; }
}

String s( "chaîne de caractère" );

printf( "affichage de la chaîne de caractère d’un objet String %s", s );

Vous aimerez peut-être aussi