0

i have a class:

class Y{ public: int x; Y(); }; 

Main:

int main(){ Y y; y.x = 10; y << mystream; return 0; } 

I just wanna to cause any action when y<<mystream is typed. I tried in my class header like those:

friend Y mystream(Y y); friend ostream mystream(ostream o, Y y) 

And etc. but nothing didn't work. Any ideas to custom this stream?

Best regards!

4
  • You'll need to overload the << operator. stackoverflow.com/questions/476272/… Commented Nov 28, 2017 at 12:32
  • The code doesn't compile. You cannot private members. Commented Nov 28, 2017 at 12:33
  • 5
    Possible duplicate of How to properly overload the << operator for an ostream? Commented Nov 28, 2017 at 12:36
  • Why y << stream instead of stream << y, since the latter is how the << operator is usually invoked on a stream. Commented Nov 28, 2017 at 12:56

3 Answers 3

1

You can overload the insertion operator "<<" to take a class A object as its LHS and an ostream object as its rhs:

class A{ public: int x; friend ostream& operator << (A& lhs, ostream& out){ out << lhs.x; return out; } }; int main(){ A a; a.x = 7; a << cout; // 7 cout << endl; return 0; } 
Sign up to request clarification or add additional context in comments.

4 Comments

The << operator should take the ostream& as its first parameter, not the second, so you can do cout << a << endl. Writing it so you do a << cout is wrong.
ok, I see the OP wrote it that way, so downvote reversed, but the point still remains
@Alnitak: I know but this is what the OP wanted.
@Alnitak: what is really wrong? In my class I am free to reverse the parameters. But I know it is something we are not used to. Especially when writing: myClassOblj << cout << anotherValue << endl; Yes it's unreadable.
0

You have to overload the '<<' operator in the class then you can use it for custom output stream. Also when passing the object of ostream, make sure that they are passed by reference. You can refer to this site for example http://www.geeksforgeeks.org/overloading-stream-insertion-operators-c/

Comments

0

I dont't need:

A a; cout<<a; // or a<<cout;

For example I can do this for cout in main:

 ostream& cause(ostream& out) { out<<"My stream is here"; return out; } int main() { cout<<cause; // Print here 'my stream is here' return 0; } 

I just wanna get this behaviour for my class instead of std::cout, so i wanna write in main:

A a; a<<cause; // i want to manipulate stream(?)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.