Results 1 to 2 of 2

Thread: Why operator overloading functions can't be members of class

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Sep 2011
    Location
    Bangalore
    Posts
    254
    Thanks
    92
    Thanked 16 Times in 16 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Windows

    Default Why operator overloading functions can't be members of class

    For example, overloading operator<<

    Qt Code:
    1. #include <iostream>
    2. #include <string>
    3. #include <vector>
    4. #include <boost/algorithm/string.hpp>
    5.  
    6. using namespace std;
    7.  
    8. class String
    9. {
    10. string d_name;
    11. public:
    12. String(string const & s) : d_name(s) {}
    13. vector<String> split(string const & delimiter = " ") const
    14. {
    15. vector<string> parts;
    16. boost::split(parts, d_name, boost::is_any_of(delimiter), boost::token_compress_on);
    17. return vector<String>(parts.begin(), parts.end());
    18. }
    19. friend ostream & operator<<(ostream & out, String & obj); // making it as friend function for the convinience of accessing private data members
    20. };
    21.  
    22. ostream & operator<<(ostream & out, String & obj)
    23. {
    24. return out << obj.d_name << endl; // If not a friend, obj.getName(): string const & getName() const { return d_string; }
    25. }
    26.  
    27. int main()
    28. {
    29. String s{"This is a test string"};
    30. vector<String> v = s.split();
    31.  
    32. vector<String>::iterator it;
    33. for(it = v.begin(); it != v.end(); ++it)
    34. cout << *it << endl;
    35. }
    To copy to clipboard, switch view to plain text mode 

    Why is the ostream & operator<<(ostream & out, String & obj) cannot be a member function?
    I mean, I don't understand the rule that - "operators << and >>, whose left operands are stream classes from the standard library which you cannot change". Kindly help me understand this.
    Thanks.
    Last edited by rawfool; 31st October 2017 at 16:33.

Similar Threads

  1. Overloading QMap << operator
    By The 11th plague of Egypt in forum Newbie
    Replies: 3
    Last Post: 14th September 2011, 19:24
  2. Operator Overloading
    By naturalpsychic in forum Newbie
    Replies: 1
    Last Post: 19th July 2011, 05:19
  3. Replies: 1
    Last Post: 9th January 2011, 07:20
  4. operator [] overloading
    By darksaga in forum General Programming
    Replies: 5
    Last Post: 8th April 2008, 15:27
  5. Static functions and class members
    By Raistlin in forum General Programming
    Replies: 5
    Last Post: 22nd December 2006, 10:00

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.