与h和cpp文件中声明的operator *运算符不匹配

时间:2016-10-20 09:10:48

标签: c++ operator-overloading

我有以下类(头文件):

class Kinetics{
    double x;
    double y;
    double z;
public:
    Kinetics();
    Kinetics(double x_, double y_, double z_);
    Kinetics(const Kinetics & obj);
    ~Kinetics();

    double get_x();
    void set_x(double x_);
    Kinetics operator + (const Kinetics & obj);
    Kinetics operator * (double c);
    void operator = (const Kinetics & obj);
};

运算符+和*已经实现(cpp):

Kinetics Kinetics::operator + (const Kinetics & obj){
    Kinetics aux(x + obj.x, y + obj.y, z + obj.z);
    return(aux);
}

Kinetics Kinetics::operator * (double c){
   Kinetics aux(x * c, y * c, z * c);
   return(aux);
}

与此相反: no match for operator*

我已在主程序中声明并包含头文件。我收到以下消息:

main.cpp:11:错误:'2.0e + 0 * v2'中'运营商*'不匹配

我无法弄清楚原因。发生此错误(主文件)的代码行是:

Kinetics v4 = 2.0 * v2;

欢迎任何建议。谢谢。

2 个答案:

答案 0 :(得分:0)

这就是为什么将大多数二元运算符声明为成员函数是一个坏主意 - 它们是不对称的。你需要

class Kinetics;
Kinetics operator *(const Kinetics& k, double c);
Kinetics operator *(double c, const Kinetics&k) { return k*c; }

class Kinetics{
    double x;
    double y;
    double z;
public:
    Kinetics();
    Kinetics(double x_, double y_, double z_);
    Kinetics(const Kinetics & obj);
    ~Kinetics();

    double get_x();
    void set_x(double x_);
    Kinetics operator + (const Kinetics & obj);
    friend Kinetics operator * (const Kinetics& k, double c);
    void operator = (const Kinetics & obj);
};

答案 1 :(得分:0)

就复合赋值运算符而言,有一种实现二元运算符的通用模式。这样可以避免对朋友的需求,并为您提供一致的行为。

在您的情况下,这看起来像这样:

class Kinetics {
  // all that stuff
public:
  Kinetics& operator +=(const Kinetics& rhs) {
    // implemented inline for less typing
    x += rhs.x;
    y += rhs.y;
    z += rhs.z;
    return *this;
  }
  Kinetics& operator *=(double rhs) {
    x *= rhs;
    y *= rhs;
    z *= rhs;
    return *this;
  }
}
// These are non-member, non-friend functions
// Again inline for my convenience
inline Kinetics operator +(Kinetics lhs, const Kinetics& rhs) {
  lhs += rhs; // lhs is already a copy
  return lhs;
}
inline Kinetics operator *(Kinetics lhs, double rhs) {
  lhs *= rhs; // You may be tempted to write "return lhs *= rhs;".
  return lhs; // Don't. That would prevent RVO.
}
inline Kinetics operator *(double lhs, Kinetics rhs) {
  rhs *= lhs; // Thanks for this being commutative
  return rhs; // this implementation works.
}