2016-09-19 192 views
0

我有我的类简单的操作符重载C++使用“*”运营商没有运营商这些操作数相匹配

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* no operator matches these operands

的问题是,我可以” t改变Vec2类,所以我需要全球运营商超载

+5

为什么你在'class FOO'里面为'Vec2'重载'*'? –

+0

我想使用FOO内的*运算符 – user63898

+0

这是什么意思?在哪里写?在标题? – user63898

回答

3

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或匿名命名空间。

+0

如果函数在头文件中,你真的*需要'inline'吗?我一直认为头中定义的函数是隐式内联的。 – Rakete1111

+1

@ Rakete1111编译器在预处理每个单元是一个大文件之后,不区分“头文件”。 –

0

你的代码没有意义。

  1. 您不需要在FOO中定义operator*函数。
  2. 由于该功能甚至不使用FOO,因此不需要使该功能成为friendFOO

简化您的代码。

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; 
}