2015-10-30 15 views
5

Data una classe:Come funziona l'operatore << sovraccarico?

struct employee { 
    string name; 
    string ID; 
    string phone; 
    string department; 
}; 

Come funziona il seguente lavoro di funzione?

ostream &operator<<(ostream &s, employee &o) 
{ 
s << o.name << endl; 
s << "Emp#: " << o.ID << endl; 
s << "Dept: " << o.department << endl; 
s << "Phone: " << o.phone << endl; 

return s; 
} 

cout << e; produce formattato uscita per un dato employee e.

uscita Esempio:

Alex Johnson 
Emp#: 5719 
Dept: Repair 
Phone: 555-0174 

non riesco a capire come funziona la funzione ostream. Come ottiene il parametro "ostream & s"? Come sovraccaricare l'operatore "< <" e come funziona l'operatore < <? Come può essere usato per scrivere tutte le informazioni su un dipendente? Qualcuno può rispondere a queste domande in parole povere?

+2

operatori overload sono zucchero principalmente sintattico per una chiamata di funzione, l'espressione 'cout << * itr' per esempio equivale a dire' operator << (cout, * itr) ', e infatti usare questa sintassi funziona esattamente allo stesso modo. – user657267

+2

Sei stanco di imparare queste cose da un libro. –

+1

Come nota a margine: la firma del sovraccarico dell'operatore di uscita dovrebbe essere "ostream & operator << (ostream & s, const employee & o)" e tutte le funzioni getter dovrebbero essere anche 'const', poiché non vi è alcun cambiamento nel' Dipendente 'istanza. –

risposta

8

Questo è chiamato risoluzione di sovraccarico. Hai scritto cout << *itr. Il compilatore lo considera come operator<<(cout, *itr);, dove cout è un'istanza se ostream e *itr è un'istanza di dipendente. Hai definito la funzione void operator<<(ostream&, employee&); che corrisponde più strettamente alla tua chiamata. Così è eseguito passando cout per s e *itr per o

1

Dato un employee e;. il seguente codice: cout << e;

chiamerà la funzione sovraccarico e passare riferimenti a cout e e.

ostream &operator<<(ostream &s, const employee &o) 
{ 
    // print the name of the employee e to cout 
    // (for our example parameters) 
    s << o.name << endl; 

    // ... 

    // return the stream itself, so multiple << can be chained 
    return s; 
} 

Sidenote: il riferimento alla employee dovrebbe essere const, dato che non cambiamo, come sottolinea πάντα ῥεῖ

Problemi correlati