次のコーディング例では string クラスを定義しています。
#include <stdlib.h> #include <iostream.h> class string { private: char* data; size_t size; public: (この項には直接関係のないさまざまな関数定義) friend ostream& operator<<(ostream&, const string&); friend istream& operator>>(istream&, string&); };
この例では、挿入演算子と抽出演算子をフレンド定義しておく必要があります。string クラスのデータ部が非公開だからです。
ostream& operator<< (ostream& ostr, const string& output) { return ostr << output.data;}
上は、string クラスに対して多重定義された演算子関数 operator<< の定義です。
cout << string1 << string2;
operator<< は、最初の引数として ostream& (ostream への参照) を受け取り、同じ ostream を返します。このため、次のように 1 つの文で挿入演算子を続けて使用することができます。