将向量用带有两个成员变量的类函数表示
表示二维向量的vector2类函数如下:
struct vector2
{
double x,y;
///构造函数指定为explicit,可以防止隐式转换
explicit vector2(double x_=0,double y_=0):x(x_),y(y_) {}
///重载 * 号 ,与实数相乘
vector2 operator * (double rhs)const
{
return vector2(x*rhs,y*rhs);
}
///返回向量的长度
double norm()const
{
return hypot(x,y);
}
///返回方向相同的单位向量
vector2 normalize()const
{
return vector2(x/norm(),y/norm());
}
///返回从x轴正方向逆时针到当前向量时的角度
double polar() const
{
return fmod(atan2(y,x)+2*PI,2*PI);
}
///计算内积(点积)
double dot(const vector2& rhs)const
{
return x*rhs.x+y*rhs.y;
}
///计算叉积(向量积)
double cross(const vector2& rhs)const
{
return x*rhs.y-y*rhs.x;
}
///将当前向量映射到rhs的结果
vector2 project(const vector2& rhs)const
{
vector2 r=rhs.normalize();
return r*r.dot(*this);
}
};