Programme surcharge opérateurs
Bonjour, j'ai un petit soucis dans mon programme suivant :
Code:
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <conio.h>
#include <iostream>
using namespace std;
class chaine
{
private :
int longueur;
char *adr;
public :
chaine();
chaine(char *texte);
void operator =(chaine &ch);
int operator ==(chaine ch);
chaine &operator +(chaine ch);
char &operator [](int i);
~chaine();
void affiche();
};
chaine::chaine() //constructeur1
{
longueur=0;
adr = new char[1];
}
chaine::chaine(char *texte) //constructeur2
{
int i;
for(i=0; texte[i]!='\0'; i++);
longueur = i;
adr = new char[longueur+1];
for(i=0; i!=(longueur+1); i++) adr[i] = texte[i];
}
void chaine::operator =(chaine &ch)
{
delete adr;
longueur = ch.longueur;
adr = new char[ch.longueur+1];
for(int i=0; i!=(longueur+1); i++) adr[i] = ch.adr[i];
}
int chaine::operator ==(chaine ch)
{
int i, res=1;
for(i=0; (i!=(longueur+1))&&(res!=0); i++) if(adr[i]!=ch.adr[i]) res=0;
return res;
}
chaine &chaine::operator +(chaine ch)
{
int i;
static chaine res;
res.longueur = longueur + ch.longueur;
res.adr = new char[res.longueur+1];
for(i=0; i!=longueur; i++) res.adr[i] = adr[i];
for(i=0; i!=ch.longueur; i++) res.adr[i+longueur] = ch.adr[i];
res.adr[res.longueur]='\0';
return res;
}
char &chaine::operator [](int i)
{
static char res='\0';
if(longueur!=0) res= *(adr+i);
return res;
}
chaine::~chaine()
{
delete adr;
}
void chaine::affiche()
{
int i;
for(i=0; i!=longueur; i++) cout << adr[i];
}
int main()
{
chaine a("Bonjour "),b("Maria"),c,d("Bonjour "),e;
if(a==b) cout << "Gagne !\n";
else cout << "Perdu !\n";
if(a==d) cout << "Gagne !\n";
else cout << "Perdu !\n";
cout << "a: ";
a.affiche();
cout << "b: ";
b.affiche();
cout << "d: ";
d.affiche();
c = a+b;
cout << "c: ";
c.affiche();
for(int i=0 ; c[i]!='\0' ; i++) cout << c[i];
getch();
} |
Celui ci m'affiche comme réponse :
Perdu !
Gagne !
a: Bonjour b: x►L ─d: á►L Þ☼L c: Bonjour x►L ─Bonjour x►L
Merci d'avance pour votre aide. Cordialement