C++ Library Reference

Defining Your Own Insertion Operator

The following example defines a string class:


#include <stdlib.h>
#include <iostream.h>


class string { 
private: 
	char* data; 
	size_t size; 

public:
	// (functions not relevant here) 

	friend ostream& operator<<(ostream&, const string&); 
	friend istream& operator>>(istream&, string&); 
}; 

The insertion and extraction operators must in this case be defined as friends because the data part of the string class is private.

 ostream& operator<< (ostream& ostr, const string& output) { return ostr << output.data; }

Here is the definition of operator<< overloaded for use with strings.

 cout << string1 << string2;

operator<< takes ostream& (that is, a reference to an ostream) as its first argument and returns the same ostream, making it possible to combine insertions in one statement.