🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: de.comp.lang.c++
Article #1691

Re: <<-operator virtual ???

#1691
From: Harald Fuchs
Date: Mon, 26 Feb 1996 18:19
54 lines
2024 bytes
Stephan Klevenz <klevenz@llt.de> writes:

> Hallo,
> vieleicht kann mir jemand bei meinem Problem helfen:


> Ich moechte den <<-Operator ueberladen und als virtuelle Methode 
> an eine abgeleitete Klasse vererben. Etwa so:

> class A
> {
>    public:
>       virtual ostream& operator << (ostream& os) 
>          {
>             return os << "bla(A)" << endl;
>          }
> };

> class B : public A
> {
>    public:     
>       virtual ostream& operator << (ostream& os)
>       {
>          A::operator << (os);	
>          return os << "bla(B)";
>       }
> };

> Als Ergebnis haette ich gerne:

> void main(void)
> {
>    A* p=new B;
>    cout << (*p);
> }

> erwartete Ausgabe: bla(A)
>                    bla(B)


> Es funktioniert aber nicht. Was mache ich falsch? Kann man den 
> <<-Operator überhaupt virtuell ueberschreiben?

Kann schon, aber das tut nicht das, was Du willst.
"virtual ostream& A::operator << (ostream&)" ist für Ausdrücke der
Form "anA << anOstream" da, nicht für sowas wie "cout << a".
Lösung:

class A {
  virtual void printOn (ostream&) const;
public:
  friend ostream& operator << (ostream& os, const A& a)
    { a.printOn (os); return os; }
};
Technical Details
Message-ID: <pubumm7xwc.fsf@themroc.colibri.de>
Path: arc1-ca.pugleaf.net!rz.uni-karlsruhe.de!not-for-mail
References: <31317EA6.714D@llt.de>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!rz.uni-karlsruhe.de!not-for-mail
From: hf@colibri.de (Harald Fuchs)
Newsgroups: de.comp.lang.c++
Subject: Re: <<-operator virtual ???
Date: 26 Feb 1996 19:19:15 +0100
Organization: Colibri GmbH, Germany
Sender: hf@themroc.colibri.de
Message-ID: <pubumm7xwc.fsf@themroc.colibri.de>
References: <31317EA6.714D@llt.de>
NNTP-Posting-Host: teco10a.teco.uni-karlsruhe.de
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit
In-reply-to: Stephan Klevenz's message of Mon, 26 Feb 1996 10:34:30 +0100
X-WWW-Home-Page: http://www.colibri.de/~hf/
X-PGP-Public-Key: finger hf@colibri.de
X-PGP-Fingerprint: 09 4E C4 A2 B2 C5 33 1A  79 80 5D 39 BD 9B 89 39
X-Disclaimer: Kore wa Colibri no iken dewa arimasen
X-Newsreader: Gnus v5.0.9