Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><em>Note:</em> You might want to look at the <a href="https://stackoverflow.com/q/4421706/140719">operator overloading FAQ</a>. </p> <hr> <p>Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the stream class or free functions. The canonical way to implement <code>operator&lt;&lt;</code> for any type is this: </p> <pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const T&amp; obj) { // stream obj's data into os return os; } </code></pre> <p>Note that it is <strong><em>not</em></strong> a member function. Also note that it takes the object to stream per <code>const</code> reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either. </p> <hr> <p>Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming</p> <pre><code>class T { public: void stream_to(std::ostream&amp;) const {os &lt;&lt; obj.data_;} private: int data_; }; </code></pre> <p>and call that from the operator: </p> <pre><code>inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const T&amp; obj) { obj.stream_to(os); return os; } </code></pre> <p>or make the operator a <code>friend</code> </p> <pre><code>class T { public: friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const T&amp;); private: int data_; }; </code></pre> <p>so that it can access the class' private parts: </p> <pre><code>inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const T&amp; obj) { os &lt;&lt; obj.data_; return os; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload