+1

operator<< cout overload

I recently watched a c++ video of "The Cherno Project" - copying and copy constructors, and on that video he overloaded cout << operator, well i got confused because he doesnt write the function declaration, only the implementation outside of the class, also he passes an ostream object as parameter, couldnt he just use This? To sum up i would like help on overloading << cout operator, and some explanation since im confused https://code.sololearn.com/cpkb0iLDHSnZ/?ref=app

10/8/2019 6:49:42 PM

Denomycor

2 Answers

New Answer

+1

Looks good. Just close the struct off with a semi-colon after the closing bracket. About operators: they are really just functions with two arguments. But as operators you can write them in infix notation. While you can write "cout << obj", it is a function call that takes the "cout" object as first argument, and the object to insert into the stream as second argument. And that is how you have to define it, as special function with keyword "operator" and two arguments, just as you have done. You'd define it as non-member function, because if you made the stream insertion operator a class member function it would belong to the cout object's class, the ostream class. But you shouldn't really fiddle around with any library classes to add operator overloads. So, you make it a non-member function overload when you customize your object output that way using stream insertion.

0

I anexed a example code, im not sure if it is correct, but i tried to reproduce it accuratly