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!

Raindrop7
  • 3,834
  • 3
  • 15
  • 27
klimucha
  • 1
  • 1
  • 3
  • You'll need to overload the << operator. https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – DThought Nov 28 '17 at 12:32
  • The code doesn't compile. You cannot private members. – Raindrop7 Nov 28 '17 at 12:33
  • 5
    Possible duplicate of [How to properly overload the << operator for an ostream?](https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream) – YSC Nov 28 '17 at 12:36
  • Why `y << stream` instead of `stream << y`, since the latter is how the `< – Alnitak Nov 28 '17 at 12:56

3 Answers3

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;
}
Raindrop7
  • 3,834
  • 3
  • 15
  • 27
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/

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(?)

klimucha
  • 1
  • 1
  • 3