|
/***********************************************************************************************************
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.