Click here to Skip to main content
15,895,746 members
Articles / Programming Languages / C++

Overloading streams

Rate me:
Please Sign up or sign in to vote.
1.67/5 (17 votes)
7 Oct 20031 min read 33.9K   370   12  
An article on overloading streams.
/***********************************************************************************************************
	This program illustrates overloading of streams i.e., 
	programmer need not to worry about which stream his object 
	is being inserted of from which stream his object extracted.	
			
			Author: Prasad Kulkarni
			Created date: Sep-27-2003
			
	All	rights reserved to SUBEX SYSTEMS Ltd.
************************************************************************************************************/
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std ;

class SomeClass 
{
public:
	explicit SomeClass(int x) // Constructor
	{
		this->x = x ;
	}
	
	int getx() const { return x; }    // Getter and
	
	void setx(int x) { this->x = x; } // Setter methods
	
	template<class T>
	friend T& operator<<(T& os, const SomeClass &d) // Overloading operator <<
	{
		os<<d.x;
		return os;
	}
	
	template<class T>
	friend T& operator>>(T& os, SomeClass &d) // Overloading operator >>
	{
		cout<<"Enter an integer: ";
		os>>d.x;
		return os;
	}
	
private:
	int x;
};


int main()
{
	SomeClass d(10); 
	cout<<d<<endl; // Output to stdout
	
	d.setx(20);
	ofstream out("hello");
	out<<d<<endl; // Output to file "hello"
	out.close(); 
	
	d.setx(30);
	ostringstream oss (ostringstream::out);
	oss<<d<<endl; // Output to string stream
	cout<<oss.str();
	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions