I found that when i create ostream operator within a class or a struct it only accepts one parameter as the second is This pointer so i tried to do it this way and it is not working though
P.S I know that i should create it outside the class or the struct as a free function But I am trying to understand why ?
struct Vector2
{
float x,y ;
Vector2(float ax , float ay )
{
x = ax ;
y = ay ;
}
std:: ostream& operator<< (std::ostream& stream )
{
return stream <<this->x<< " , "<< this->y ;
}
}
When <<
is overloaded, a << b
means either
operator<<(a,b)
if the overload is a free function, or
a.operator<<(b)
if it is a member.
That is, for an operator defined as a member, the left-hand argument is *this
, and you need to write
Vector2 v;
v << std::cout;
wihch is equivalent to
Vector2 v;
v.operator<<(std::cout);