views:

102

answers:

3

myclass is a c++ class writed by me . and when I write

myclass x;
cout << x;   // how to output is " 10 " or "20" like intger or float value 
+2  A: 

it's very easy, just implement :

std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
   os << foo.var;
   return os;
}

You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)

Tristram Gräbener
That is an infinitely recursive function. And it got an upvote! You've got to love the weekend on SO!
anon
Oh my... I feel ashamed :(
Tristram Gräbener
+9  A: 

Typically by overloading operator<< for your class:

struct myclass { 
    int i;
};

std::ostream &operator<<(std::ostream &os, myclass const &m) { 
    return os << m.i;
}

int main() { 
    myclass x(10);

    std::cout << x;
    return 0;
}
Jerry Coffin
+5  A: 

You need to overload the << operator,

std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
      os << obj.somevalue;
      return os;
}

Then when you do cout << x (where x is of type myclass in your case), it would output whatever you've told it to in the method. In the case of the example above it would be the x.somevalue member.

If the type of the member can't be added directly to an ostream, then you would need to overload the << operator for that type also, using the same method as above.

Rich Adams
That's the left shift operator, not the "stream operator". In the context of Iostreams, it's either the insertion or extraction operator, but it is never the stream operator.
Billy ONeal
Sorry, yes you're right. That's just what I've called it in my head since I tend to use it only when dealing with streams. In this case it would be the insertion operator as you say, rather than just stream operator. I've updated my answer to remove that bit.
Rich Adams