HackerRank Solution: Overloading Ostream Operator in C++

preview_player
Показать описание
HackerRank solution for Overloading Ostream Operator in C++. Learn how to overload the ostream operator in C++. We are referring to the output stream operator, also known as the insertion operator. To do that, we will write a function that will return a reference to the output stream object (ostream), and then use the operator keyword, followed by the insertion operator. We will pass our operator overloading function two parameters: one is going to be a reference to our ostream object, and the other one is going to be a reference to our custom object. Notice that we are creating that function outside our custom class in our program.

Finally, when we are using the output stream, we return it. In our program, we can then use the cout object in C++ along with our custom object to display specific details of our object, because we have overloaded the ostream operator.

Рекомендации по теме
Комментарии
Автор

Just a little refinement: as member functions first_name() and last_name() are declared const, you should declare the arguments of the << operator as follows:

ostream& operator<<(ostream& out, const Person& p);

It is more safe to declare Person argument as 'const' because the operator << can not modify it even by accident.

Anyway, you did a good work with this video, keep up!

imrefoldesi
Автор

Very clear explanation, thanks a bunch! :D

strangeanimations
Автор

I am writing my program whose topic is overloading. However, I allocate the memory in binary search trees. And in ostream operator, I need to access the members of the root to overload the operators +, +=, = and <<
Any idea to help me about that?
I think that I need to make recursively get function to access the members of BST
Thanks

yakupoztuna
Автор

Thanks myan! btw why we have used ostream there??? SUBSCRIBED ;)

bibekdhkl