how to print ostream&

Create a simple class containing an int and overload the operator+ as a member function.Also provide a print() member function that takes an ostream& as an arguement and prints to that ostream&. Test your class to show that it works correctly.

#include <iostream>
using namespace std;

class Simple
{
int x;
public:
Simple operator +(const Simple &a);
void print(ostream& os);
};

Simple Simple::operator+(const Simple &a)
{
return (x+a.x);
}

void Simple::print(ostream& os)
{
//???
}
do you know about the stream insertion and extraction operators << and >>.

have you not done anything like ?
1
2
int z = 2;
cout << z << endl;

1
2
3
4
void Simple::print(ostream& os)
{
  os << this.x << "\n";
}


Usually we don't do printing in such a way. We want the calling code to be intuitive like cout << objSimple << "\n";

But yours still work like objSimple.print(cout); // this is not intuitive but get the job done also

Topic archived. No new replies allowed.