When I'm trying to overload operator<< for char and use it which std::cout something is wrong.During compilation I don't have any errors but when i type ./a.outi see Segmentation fault (core dumped).
This is code:
#include <iostream>
std::ostream & operator<<(std::ostream & COUT, char letter)
{
COUT << letter;
return COUT;
}
int main(void)
{
std::cout << 'l';
}
Thanks for every help.
The problem is that the statement
will invoke your own overloaded function, leading to infinite recursion.
You need to explicitly call the "normal" overloaded function:
On a different note, because the
<<operator returns a reference to the stream, you can use it in your own function as a single statement:For characters and strings, it's a nonmember function, for everything else it's a member function. So for example
intyou need to call the member function instead: