【问题标题】:Creating scalar multiplication operator for 2d vector class为二维向量类创建标量乘法运算符
【发布时间】:2018-10-16 00:02:06
【问题描述】:

所以我正在为一个类创建一个 2D 矢量类,在该类中,我在 x-y 平面上创建具有质量和半径的圆形对象之间的碰撞。所以每次发生碰撞时,我都需要更新碰撞的两个圆的速度,这取决于像质量和半径这样的标量数字以及石头的动能(标量)和动量(2d 矢量)(因为动量和能量守恒,你可以解决任何一个的动量和能量)。除标量乘法外,所有方法都有效。除非你们特别要求我向其他人展示,否则我只会在下面展示该方法

这是我的二维矢量类

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')

如果我应该提供更多信息,请告诉我

【问题讨论】:

  • 你能提供一个minimal reproducible example吗?您只需要提供足够的代码来说明您的重载运算符。 collide() 函数比说明这一点所需的复杂得多。我建议使用您的 vector2d 类创建一个文件,并且只创建您的问题所需的成员。还包括一个main() 函数来说明你想要做什么。当您在此处发布代码时,任何人都应该能够复制和粘贴它并得到与您所询问的完全相同的编译器错误。

标签: c++ class game-physics


【解决方案1】:

您的代码将doublevector2d 相乘。这不会激活操作员,因为操作员首先会期望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 上使用引用对我来说似乎是浪费时间。

【讨论】:

  • 我尝试让我的操作员看起来像你之前发布的那个,但它会给我带来与以前相同的错误以及请求多个参数的额外错误
  • 不要把new操作符放到类里;把它放在课外。这几乎肯定是导致这些错误的原因。
猜你喜欢
  • 2015-02-23
  • 2011-08-11
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-30
相关资源
最近更新 更多