Surcharge d'operateur

cs_AngeloVivaldi Messages postés 60 Date d'inscription dimanche 8 décembre 2002 Statut Membre Dernière intervention 1 juillet 2004 - 28 juil. 2003 à 22:27
tcok Messages postés 61 Date d'inscription samedi 7 juin 2003 Statut Membre Dernière intervention 3 août 2005 - 29 juil. 2003 à 14:15
Salut, je voudrai redefinir cout dans de iostream.h pour qu'il affiche un membre de ma class au lieu d'afficher l'adresse de l'objet :

Par exemple, pour une class X, j'ai écrit pour redéfinir l'opérateur :

ostream operator<<(X p)
{
cout << X.membre;
}

pour que lorsque j'écrit :

X c;
cout << c;

Cela affiche le membre. Mais je n'y arrive pas, quelqu'un peut m'aider ???
Merci !

3 réponses

tcok Messages postés 61 Date d'inscription samedi 7 juin 2003 Statut Membre Dernière intervention 3 août 2005
28 juil. 2003 à 22:37
dans ta classe X,

declaration :
friend ostream& operator<<(ostream& ostr, const &X c)

implementation :
ostream& operator<<(ostream& thestream, const &X c)
{
thestream << c.membre;
return thestream;
}
0
cs_AngeloVivaldi Messages postés 60 Date d'inscription dimanche 8 décembre 2002 Statut Membre Dernière intervention 1 juillet 2004
29 juil. 2003 à 01:58
Il y a 9 erreur lors de la compilation avec ta méthode, et toutes dans ta fonction :

b.cpp(29) : error C2146: syntax error : missing ',' before identifier 'c'
b.cpp(29) : error C2061: syntax error : identifier 'c'
b.cpp(30) : error C2143: syntax error : missing ';' before 'private'
b.cpp(36) : error C2039: '<<' : is not a member of 'Tin'
b.cpp(4) : see declaration of 'Tin'
b.cpp(36) : error C2146: syntax error : missing ',' before identifier 'c'
b.cpp(36) : error C2061: syntax error : identifier 'c'
b.cpp(38) : error C2065: 'c' : undeclared identifier
b.cpp(38) : error C2228: left of '.Str' must have class/struct/union type
b.cpp(46) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class Tin' (or there is no acceptable conversion)
0
tcok Messages postés 61 Date d'inscription samedi 7 juin 2003 Statut Membre Dernière intervention 3 août 2005
29 juil. 2003 à 14:15
voici un petit exemple vite fait qui compile tres bien chez moi ...

#include "stdafx.h"
#include 

#define cout std::cout

class Test
{
public:
Test() : membre(0) {};
virtual ~Test() {};

friend std::ostream& operator<<(std::ostream& ostr, const Test &c);

int membre;
};

std::ostream& operator<<(std::ostream& thestream, const Test &c)
{
thestream << c.membre;
return thestream;
}

int main(int argc, char* argv[])
{
Test essai;

cout << essai << std::endl;
cout << "ok" << std::endl;
return 0;
}


@+ tcok
0
Rejoignez-nous