Ja! Da es häufig sinnvoll ist, solche Operatoren zur Verfügung zu haben (z.B. skalare Multiplikation von links) wurde das Schlüsselword friend in C++ aufgenommen.
Als friend in der Klasse deklarierte Funktionen haben das Recht auf private Komponenten zuzugreifen!
Beispiel der Ein- und Ausgabe über die Standard-Ströme:
Deklaration:
class CVector {
...
friend ostream& operator<<( // output to stream
ostream& os,
const CVector& v
);
friend istream& operator>>( // input from stream
istream& is,
CVector& v
);
...
};
Implementierung:
ostream& operator<<(
ostream& os,
const CVector& v
) {
os << "( ";
for(int i=0;i<v.dimension;i++) {
os << v.vector[i] << " ";
}
os << ") " << endl;
return(os);
}
istream& operator>>(
istream& is,
CVector& v
) {
cout << "vector(" << v.dimension << ") = ";
for(int i=0;i<v.dimension;i++) {
is >> v.vector[i];
}
return(is);
}
Man beachte: