myclass
is a C++ class written by me and when I write:
myclass x;
cout << x;
How do I output 10
or 20.2
, like an integer
or a float
value?
myclass
is a C++ class written by me and when I write:
myclass x;
cout << x;
How do I output 10
or 20.2
, like an integer
or a float
value?
Alternative:
Typically by overloading
operator<<
for your class:You need to overload the
<<
operator,Then when you do
cout << x
(wherex
is of typemyclass
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 thex.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.it's very easy, just implement :
You need to return a reference to os in order to chain the outpout (cout << foo << 42 << endl)