[c++] operator+

Résolu/Fermé
jacinthe87 Messages postés 194 Date d'inscription mercredi 4 février 2009 Statut Membre Dernière intervention 15 juillet 2010 - 2 mars 2009 à 21:21
 loupius - 2 mars 2009 à 21:33
Bonjour,

je veux concaténer 2 chaines dans une autre chaine, mon probleme c'est que lors de l'affichage la 2eme chaine ne s'affiche pas complètement.
par exemple si j'ai ch1="bonjour" et ch2="monde"
dans l'affichage j'obtiens : bonjour mon

voila ma fonction:
Chaine  Chaine::operator+(const Chaine & a)
{ 
 Chaine c;
    
 c.longueur=longueur+a.longueur;
 c.mot=new char[c.longueur];
             for(int i=0;i<longueur;i++)
                     c.mot[i]=mot[i];
             for(int j=0;j<a.longueur;j++)
                     c.mot[j+a.longueur+1]=a.mot[j];
return c;       
}

1 réponse

Je crois qu'il y a une erreur:
for(int j=0;j<a.longueur;j++)
   c.mot[j+a.longueur+1]=a.mot[j];
ce serait plutôt: c.mot[j+longueur+1]=a.mot[j];
Personnellement, j'aurais écrit:
Chaine  Chaine::operator+(const Chaine & a)
{ 
 Chaine c;
    
 c.longueur=longueur+a.longueur;
 c.mot=new char[c.longueur];
 int i, j;
 for (i=0; i<longueur; i++)
   c.mot[i] = mot[i];
 for (j=0; j<a.longueur; j++)
   c.mot[i + j] = a.mot[j];
return c;       
}
1