ostream überladen



  • ich muss den << überladen
    das hab ich bis jetzt
    steht in meiner klasseunter public

    ostream & operator<< (ostream &);

    address::print()
    {

    }

    da muss das rein irgendwie denn mit der funktion soll dasdann aufgerufen werden
    wiemach ich das?! (die classe hat 4string variablen die ausgegeben werden sollen die classe heist address

    UND WENN JETZT WIEDER IRGENDWER MIT RTFM KOMMT UND NEN LINK ZU IRGENDEINER SCHEISS POSTED DIE DAMIT NIX ZUTUN HAT KRIG ICH NEN AUSFLIPPER UND MUSS DEN LEIDER TÖTEN

    danke im voraus gruß Rio 🙂



  • Wie wäre es mit

    // Ausgabestream überladen
    ostream& operator<<(ostream& os)
    {
    	os << String1 << endl;
            os << String2 << endl;
    	return os;
    }
    


  • Der operator<< darf in diesem Fall kein Member sein.

    ostream& operator<< (ostream& s, const adresse& a)
    {
        s << a.wasauchimmer;
        return s;
    }
    


  • Hier mal ein komplettes Beispiel:

    #include <iostream.h>
    
    class Geld
    {
    	int euro;
    	int cent;
    
    	public:
    		Geld(int e=0, int c=0):euro(e), cent(c) {}
    		int getEuro()	{ return euro; }
    		void setEuro(int x) { euro = x; }
    		int getCent() { return cent; }
    		void setCent(int x);
    		void print()
    		{
    			cout << euro << "." << cent << endl;
    		}
    		friend Geld operator+(Geld a, Geld b);
    		friend Geld operator-(Geld a, Geld b);
    		friend ostream& operator<<(ostream& os, Geld& m);
    		friend istream& operator>>(istream& is, Geld& m);
    };
    
    /* Abfrage:
    *  euro = euro / 100
    *  cent = euro % 100
    */
    
    Geld operator+(Geld a, Geld b)
    {
    	Geld c;
    	c.euro = a.euro + b.euro;
    	c.cent = a.cent + b.cent;
    	c.euro += c.cent / 100;
    	c.cent = c.cent % 100;
    
    	return c;
    }
    
    Geld operator-(Geld a, Geld b)
    {
    	Geld c;
    	c.euro = a.euro - b.euro;
    	c.cent = a.cent - b.cent;
    
    	return c;
    }
    
    void main()
    {
    	Geld fritz(10,10);
    	Geld hans(20,10);
    	Geld wir;
    	wir = hans - fritz;
    	wir.print();
    	cin >> wir;				// Mit überladendem Eingabestream
    	cout << wir << endl;	// Mit überladendem Ausgabestream
    
    }
    
    // Ausgabestream überladen
    ostream& operator<<(ostream& os, Geld& m)
    {
    	os << m.euro << " Euro und " << m.cent << " Cent";
    	return os;
    }
    
    // Eingabestream überladen
    istream& operator>>(istream& is, Geld& m)
    {
    	cout << "Euro: ";
    	is >> m.euro;
    
    	cout << "Cent: ";
    	is >> m.cent;
    
    	return is;
    }
    

    Edit by SideWinder: Aus CODE-Tags CPP-Tags gemacht und damit das Syntax-Coloring aktiviert 🙂


Anmelden zum Antworten