how can i overload “<<” operator (for cout) so i could do “cout” to a class k
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The canonical implementation of the output operator for any type
Tis this:Note that output stream operators commonly are not member functions. (That’s because for binary operators to be member functions they have to be members of their left-hand argument’s type. That’s a stream, however, and not your own type. There is the exception of a few overloads of
operator<<()for some built-ins, which are members of the output stream class.)Therefor, if not all data of
Tis publicly accessible, this operator has to be a friend ofTor the operator calls a public function which does the streaming:
The advantage of the latter is that the
write_to_stream()member function can bevirtual(and pure), allowing polymorphic classes to be streamed.If you want to be fancy and support all kinds of streams, you’d have to templatize that:
(Templates, however, don’t work with virtual functions.)