所以我正在为一个类创建一个二维 vector 类,在该类中我在 x-y 平面上创建具有质量和半径的圆形对象之间的碰撞。因此,每次发生碰撞时,我都需要更新碰撞的两个圆的速度,这取决于质量和半径等标量以及动能(标量)和石头的动量(二维 vector )(因为动量和能量守恒,你可以解决其中任何一个的动量和能量)。除了标量乘法,所有方法都有效。除非你们特别要求我展示其他方法,否则我只会在下面展示该方法
这是我的二维 vector 类
class vector2d {
public:
double x;
double y;
// Constructor
vector2d() { x=0; y=0; }
vector2d(double_x, double_y) { x=_x; y=_y;}
.
.
.
vector2d operator*(const double& scalar) const {
return {x * scalar, y * scalar };
}
这是另一个类中的方法,它在碰撞后更新速度
void collide(Ball *s) {
// Make sure move is called before this to update the position vector'
vec2d diff_pos_s1 = this->init_pos - s->init_pos;
vec2d diff_vel_s1 = this->velocity - s->velocity;
double mass_ratio_s1 = (2 * s->mass) / (this->mass + s->mass);
double num_s1 = diff_pos_s1.dot_product(diff_vel_s1);
double denom_s1 = diff_pos_s1.dot_product(diff_pos_s1);
vec2d v1 = this->velocity - (mass_ratio_s1 * (num_s1 / denom_s1) * diff_pos_s1);
vec2d diff_pos_s2 = s->init_pos - this->init_pos;
vec2d diff_vel_s2 = s->velocity - this->velocity;
double mass_ratio_s2 = (2 * this->mass) / (this->mass + s->mass);
double num_s2 = diff_vel_s2.dot_product(diff_pos_s2);
double denom_s2 = diff_pos_s2.dot_product(diff_pos_s2);
vec2d v2 = s->velocity - (mass_ratio_s2 * (num_s2 / denom_s2) * diff_pos_s2);
this->velocity = v1;
s->velocity = v2;
}
这是计算能量和动量的方法
double energy() const {
return 0.5 * (mass * velocity * velocity) ;
}
// Calculates the momentum of the balls
vec2d momentum() const {
return mass * velocity;
}
以下是产生的错误:
error: no match for 'operator*' (operand types are 'double' and 'vector2d')
error: no match for 'operator*' (operand types are 'const double' and 'vector2d')
让我知道是否应该提供更多信息
最佳答案
您的代码将 double
乘以 vector2d
。这不会激活运算符,因为运算符将首先期望 vector2d
。你应该有
vec2d v1 = this->velocity - (diff_pos_s1 * (mass_ratio_s1 * (num_s1 / denom_s1)));
或者编写一个vector2d operator*(double, vector2d)
,例如
vector2d operator *(const double & scalar, const vector2d & other) {
return { other.x * scalar, other.y*scalar };
}
顺便说一句,对我来说,在 const double
上使用引用似乎是在浪费时间。
关于c++ - 为二维 vector 类创建标量乘法运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192886/