Ostream运算符过载



我发现当我在类或结构中创建ostream运算符时它只接受一个参数,因为第二个参数是This指针所以我试着这样做,但通过它不起作用

p.S我知道我应该在类或结构之外创建它作为一个自由函数,但我正在努力理解为什么?

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 ; 
}
}

<<过载时,a << b表示

operator<<(a,b)

如果过载是自由功能,或者

a.operator<<(b)

如果它是成员。

也就是说,对于定义为成员的运算符,左边的参数是*this,您需要编写

Vector2 v;
v << std::cout;

wihch相当于

Vector2 v;
v.operator<<(std::cout);

相关内容

最新更新