【サンプル】

#include <cstdlib>
#include <iostream>
#include <sstream>

using namespace std;


class pen
{
public:
   pen(const string& str)
    :m_str(str)
   {};


   //friend宣言
   friend ostream& operator << (ostream& os, const pen& p);


private:
   string m_str;
};


//演算子の定義
ostream& operator << (ostream& os, const pen& p)
{
   os << p.m_str;
   return os;
};



int main(int argc, char *argv[])
{
   pen p("ball pen");

   cout << p << endl;


   //他のストリーム(例えば文字列ストリーム)も!
   ostringstream str;
   str << p;
   cout << str.str() << endl;


   system("PAUSE");
   return EXIT_SUCCESS;
}



【出力】

ball pen

ball pen

【説明】

独自のクラスに出力ストリームを使えるようにするには、

外部で、operator << を定義してあげればよいです。


このとき、もし独自クラスのprivateのメンバー変数を直接使用する場合、

operator << を friend 宣言してあげないといけません。


また、この外部定義1つで、他のストリームにも適用できるようになります。

ここでは文字列ストリームを例にしましたが、ファイルストリームにも適用できます。

これは、ostreamがすべてのストリームの基底になっているので、自動的に親クラスにキャストされるからです。



参考:

templateクラスの外部で、friend関数のコードを書くには?

数字や文字列を次々に連結してstringに出力するには?
出力ストリームcoutなどの状態変更の有効期限を関数内だけにするには?