c++ - Why doesn't this << overload compile -


I can not understand why the following code does not compile. Syntax is similar to my other operator overload. & Lt; & Lt; Should be Overload Friend? If so, why? Thanks for any help.

This does not work -

  #include "stdafx.h" #include & lt; Iostream & gt; # Include & lt; Fstream & gt; #include & lt; String & gt; Class test {public: Clear test: M_vir (var) {} std :: ostream & amp; For operator & lt; & Lt; (Stud :: Ostream End Stream) {Return Stream & lt; & Lt; M_Var; } Private: int m_Var; }; Int _tmain (int argc, _TCHAR * argv []) {test temp (5); Std :: cout & lt; & Lt; Temporary; Return 0; }  

This works -

  #include "stdafx.h" #include & lt; Iostream & gt; # Include & lt; Fstream & gt; #include & lt; String & gt; Class Test {Public: Clear Test: M_vir (var) {} Friend Study :: Ostream & amp; For operator & lt; & Lt; (Study :: Ostream End Stream, Test and Tump); Private: int m_Var; }; Std :: ostream & amp; For operator & lt; & Lt; (Study :: Ostream End Stream, Test and Tump) {Return Stream & lt; & Lt; Temp.m_Var; }; Int _tmain (int argc, _TCHAR * argv []) {test temp (5); Std :: cout & lt; & Lt; Temporary; Return 0; }   

This is the basic reason that stream operators should be friends.

Take this code:

  Straight Gizmo {ostream & amp; Operator & lt; & Lt; (Ostream & os) const {os & lt; & Lt; 42; }}; Int main () {Gizmo g; Cout & lt; & Lt; G; Return 0; }  

References to call cout & lt; & Lt; G; When the compiler aggregates this function, it first tries:

  cout.operator & lt; & Lt; (G);  

... and if it is not found, then it appears for the following in the global namespace:

  operator < & Lt; (Cout, g);  

... and if that is not found, then it can not be compiled.

But when you try to apply the stream entry operator as a member of Gizmo, you are hoping that the compiler will solve your code in this way:

  g.operator & lt; & Lt; (Cout);  

... that can not be done unless you change your code by:

  g  

... which is not obvious to who you are going for.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -