-
operators << and >>
How to overload the << and >> operator
i have class like this:
Code:
class kom
{
private:
int a,b;
char d;
float x,y;
public:
kom(){}
kom(int l,int m,char n,float i,float j)
{
a=l; b=m; d=n; i=x; y=j;
}
}
i now a litle how to do this
Code:
friend kom operator<<(ostream, out_file)
{
cout<<a<<b<<d<<x<<y<<'\n';
}
i know this is not correct but i dont know the right way
-
1. You declare it to be a friend only in the class body.
Code:
class kom
{
friend ostream& operator<<(ostream& out, const kom&);
//other data
}; //<===Don't forget the semicolon after the class declaration
you define it elsewhere without the friend directive because outside the class it would mean it's a friend to the global scope, which wouldn't be much use
Code:
class kom
{
//other data
};
//defined outside the scope of kom
ostream& operator<<(ostream& out, const kom&)
{
//don't use cout, cout is the standard output, you want
//to use any output stream such as a file or string stream or any
//other stream object
out <<a<<b<<d<<x<<y<<'\n';
return out; //remember to return it.
}
now you can use it as such
Code:
int main()
{
ofStream outfile("output.txt");
ostringstream outsstream;
kom aKom;
//do whatever it is you want with your class
cout << aKom;
outfile << aKom;
outsstream << aKom;
return 0;
}