title: Friend function defining an ostream operator
body: <p>I would like to define an ostream operator to let me easily output variables of type <code>alglib::complex</code>. To provide a working example without including the alglib library I'll instead overload the output of <code>complex&lt;double&gt;</code> below (this clarification because of an earlier version of the question). In the header file "my_class.h" I have</p>
  
  <pre><code>using namespace std;
  #include &lt;complex&gt;
  #include &lt;iostream&gt;
  
  class my_class {
  
      public:
  
      ostream&amp; operator &lt;&lt; (std::ostream&amp; os, complex&lt;double&gt; a) {
          os &lt;&lt; "(" &lt;&lt; real(a) &lt;&lt; "," &lt;&lt; imag(a) &lt;&lt; ")";
          return os;
      }
  
      void output(complex&lt;double&gt;);
  
      my_class() {}
      ~my_class() {}
  };
  </code></pre>
  
  <p>And in the source file "my_class.cpp" I have </p>
  
  <pre><code>#include "my_class.h"
  
  void my_class::output(complex&lt;double&gt; cd) {
      cout &lt;&lt; cd &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Finally I have a main method file "run_my_class.cpp":</p>
  
  <pre><code>#include "my_class.h"
  
  int main(int argc, const char* argv[]) {
  
      my_class obj;
      complex&lt;double&gt; cd=complex&lt;double&gt;(1.0,-1.0);
      obj.output(cd);
  
  }
  </code></pre>
  
  <p>I try to compile using</p>
  
  <pre><code>g++ -c my_class.cpp
  </code></pre>
  
  <p>but this gives me the error </p>
  
  <pre><code>my_class.h:9:62: error: ‘std::ostream&amp; my_class::operator&lt;&lt;(std::ostream&amp;, std::complex&lt;double&gt;)’ must take exactly one argument
   ostream&amp; operator &lt;&lt; (std::ostream&amp; os, complex&lt;double&gt; a) {
  </code></pre>
  
  <p>However, if I define the operator as a friend, namely <code>friend ostream&amp; operator &lt;&lt; (std::ostream&amp; os, complex&lt;double&gt; a)</code>, it compiles and I compile the main method:</p>
  
  <pre><code>g++ run_my_class.cpp my_class.o -o run_my_class
  </code></pre>
  
  <p>And it works as it should. However this is not what it seems the <code>friend</code> keyword is for. Is there a better way to make this work?</p>