Wednesday, 15 April 2015

How to overload the << operator based on a method display already defined? -


Let me & lt; & Lt; Operator for my class from a previously defined method display does not receive any match compiler error for the operator & lt; & Lt;.

Here's a minimal example:

  #include & lt; Iostream & gt; using namespace std; Classes Myclass {Public: Myclass () {} Ostream & amp; Exhibit (Ostream & amp Out); Constant {out & lt; & Lt; "Display message" & lt; & Lt; Endl; Return; } Ostream & amp; amp; For operator & lt; & Lt; (Ostream & amp; Out) Conte (Ostream & Output = Display (Out); Return Output;}}; Int main () {MyClass C1; Cout & lt; c1 & lt; endl ; Return 0;}  

However C1.display (cout); Woks without problems!

You have MyClass as member function as the operator > Defined, therefore, you should call it like member functions (the object on the left, the parameters on the right), such as:

  C1 & l T; & lt; court;  

But it does not seem that what you want. Maybe you want to be able to call it like this:

  cout  

In that case the function can not be a member of MyClass . cout , or must be a member of Free Task (outside of any class) and in this case it should Function will work because you do not change the definition of cout I can.

Then, to declare operator and lieutenant; & Lt; As a free function, there should be two arguments (left hand and right hand):

  ostream & amp; For operator & lt; & Lt; (Ostream & Out, const MyClass & amp; c) {...}  

Now you can place it on ostream on the left and MyClass Calling Object on the right, like this:

  cout & lt; & Lt; C1;  

No comments:

Post a Comment