For example, overloading operator<<
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
class String
{
string d_name;
public:
String(string const & s) : d_name(s) {}
vector<String> split(string const & delimiter = " ") const
{
vector<string> parts;
boost::split(parts, d_name, boost::is_any_of(delimiter), boost::token_compress_on);
return vector<String>(parts.begin(), parts.end());
}
friend ostream & operator<<(ostream & out, String & obj); // making it as friend function for the convinience of accessing private data members
};
ostream & operator<<(ostream & out, String & obj)
{
return out << obj.d_name << endl; // If not a friend, obj.getName(): string const & getName() const { return d_string; }
}
int main()
{
String s{"This is a test string"};
vector<String> v = s.split();
vector<String>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
}
#include <iostream>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
using namespace std;
class String
{
string d_name;
public:
String(string const & s) : d_name(s) {}
vector<String> split(string const & delimiter = " ") const
{
vector<string> parts;
boost::split(parts, d_name, boost::is_any_of(delimiter), boost::token_compress_on);
return vector<String>(parts.begin(), parts.end());
}
friend ostream & operator<<(ostream & out, String & obj); // making it as friend function for the convinience of accessing private data members
};
ostream & operator<<(ostream & out, String & obj)
{
return out << obj.d_name << endl; // If not a friend, obj.getName(): string const & getName() const { return d_string; }
}
int main()
{
String s{"This is a test string"};
vector<String> v = s.split();
vector<String>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
cout << *it << endl;
}
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.
Bookmarks