【问题标题】:c++ using "*" operator no operator matches these operandsc++ 使用“*”运算符没有运算符匹配这些操作数
【发布时间】:2016-09-19 05:26:17
【问题描述】:

我的班级中有简单的运算符重载

class Vec2
{
public:
    Vec2(float x1,float y1)
    {
       x = x1;
       y = y1;
    }
    float x;
    float y;
};

class FOO {
private:
    friend Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
    {
            return Vec2(point1.x * point2.x, point1.y * point2.y);
    }

    Vec2 mul(Vec2 p);
};

Vec2 FOO::mul(Vec2 p)
{
    Vec2 point = p * Vec2(1,-1);
    return point;
}

但是这个乘法给了我这个错误:

operator*没有运算符匹配这些操作数

问题是我不能改变 Vec2 类,所以我需要全局运算符重载

【问题讨论】:

  • 你为什么在Vec2class FOO内部重载*
  • 我想在 FOO 中使用 * 运算符
  • 这是什么意思?在哪里写呢?在标题中??

标签: c++ operator-overloading


【解决方案1】:

operator* 定义不应在 class FOO 内。把它放在任何类定义之外:

inline Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
    return Vec2(point1.x * point2.x, point1.y * point2.y);
}

如果它在头文件中,则需要 inline 关键字。然后,您可以在 FOO 和其他任何地方使用运算符。

无法将运算符限制为只能在 FOO 方法中使用。函数可见性不是这样工作的。您可以做的最接近的做法是仅在一些也具有使用点的.cpp 文件中声明operator* 重载,并将其标记为static 或匿名命名空间。

【讨论】:

  • 如果函数在头文件中,你真的需要inline吗?我一直认为头文件中定义的函数是隐式内联的。
  • @Rakete1111 编译器不区分“头文件”,预处理后每个单元都是一个大文件。
【解决方案2】:

您的代码没有意义。

  1. 您无需在FOO 中定义operator* 函数。
  2. 您不需要将该函数设为 friendFOO,因为该函数甚至不使用 FOO

简化您的代码。

class Vec2
{
   public:
      Vec2(float x1 ,float y1)
      {
         x = x1;
         y = y1;
      }
      float x;
      float y;

};

// This does not need to be defined inside FOO.
Vec2 operator*(const Vec2 &point1, const Vec2 &point2)
{
   return Vec2(point1.x * point2.x, point1.y * point2.y);
}

class FOO {
   private:
      // No need for the friend declaration.
      Vec2 mul(Vec2 p);
};    

Vec2 FOO::mul(Vec2 p)
{    
   // Works fine without the friend declaration.
   Vec2 point = p * Vec2(1,-1);
   return point;
}

【讨论】:

    猜你喜欢
    • 2018-05-02
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多