944,008 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 592
  • C++ RSS
Nov 12th, 2008
0

<< operator overloading

Expand Post »
Can anybody tell me how to overload << operator ?
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
san_sarangkar is offline Offline
16 posts
since Sep 2008
Nov 12th, 2008
0

Re: << operator overloading

10 seconds with google finds this

But, I would not put the << endl in the overload - that limits how you can use it in building up outputs from multiple object.
Last edited by vmanes; Nov 12th, 2008 at 3:16 am.
Reputation Points: 1268
Solved Threads: 228
Posting Virtuoso
vmanes is offline Offline
1,895 posts
since Aug 2007
Jul 16th, 2009
0

Re: << operator overloading

in order to be able to overload an operator<<,it must be declared as the friend of the class.
here is the overloarding syntax:
//declaring as the class friend
friend std::ostream operator<<(std::ostream &output,classname out);
//overloading it outside the class
std::ostream operator<<(std::ostream & output,classname out)
{
//function specification here
//if you want to display the word do as for example
output<<"do";
return output;
}
Reputation Points: 10
Solved Threads: 0
Newbie Poster
khotso is offline Offline
5 posts
since Jul 2009
Jul 16th, 2009
0

Re: << operator overloading

Quote ...
in order to be able to overload an operator<<,it must be declared as the friend of the class.
Only if the overloaded operator needs access to the private or protected members of the class. If you only touch the public interface, the operator does not need to be a friend:
C++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. namespace Daniweb
  6. {
  7. class Test
  8. {
  9. int _x;
  10. public:
  11. Test(int x): _x(x) {}
  12. int operator()() const { return _x; }
  13. };
  14.  
  15. ostream& operator<<(ostream& os, const Test t)
  16. {
  17. return os << t();
  18. }
  19. }
  20.  
  21. int main()
  22. {
  23. cout << Daniweb::Test(15) << '\n';
  24. }
Reputation Points: 1446
Solved Threads: 135
Practically a Master Poster
Tom Gunn is offline Offline
681 posts
since Jun 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Choosing the right data from a txt file
Next Thread in C++ Forum Timeline: Problem: only one character being read





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC