Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding operator<< for console output doesn't work for member variables
    primarykey
    data
    text
    <p>I have a class MyList that overrides the <code>&lt;&lt;</code> operator to be able to log itself to the console:</p> <pre><code>class MyList { public: vector&lt;int&gt; *numbers; }; ostream&amp; operator&lt;&lt;(ostream&amp; os, MyList&amp; l); </code></pre> <p>Implementation:</p> <pre><code>ostream&amp; operator&lt;&lt;(ostream&amp; os, MyList&amp; l) { for (int i = 0; i &lt; l.numbers-&gt;size(); i++) { os &lt;&lt; l.numbers-&gt;at(i); } return os; } </code></pre> <p>In an other class I have a member variable of type MyList and I can't print it to the console. Interestingly a local MyList variable works fine:</p> <pre><code>class A { public: MyList list; void someMethod() const; }; </code></pre> <p>Implementation:</p> <pre><code>void A::someMethod() const { MyList local; // Set up local list. cout &lt;&lt; "Local:" &lt;&lt; local; // OK! cout &lt;&lt; "Member:" &lt;&lt; list; // ERROR! } </code></pre> <p><strong>This is the error message:</strong></p> <pre><code>Invalid operands to binary expression ('basic_ostream&lt;char, std::__1::char_traits&lt;char&gt;&gt;' and 'const MyList') </code></pre> <p>Xcode's auto-fix recommends to reference <code>list</code>:</p> <pre><code>cout &lt;&lt; "Member:" &lt;&lt; &amp;list; </code></pre> <p>This will compile, but (obviously) it prints the adress of <code>list</code> and not my content. I don't understand what the difference is between those two variables in regards to the <code>&lt;&lt;</code> operator. Could anybody explain?</p>
    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.
 

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