重载 C++ 类型以处理自定义 class

Overloading a C++ type to handle a custom class

目前只是在处理重载类型和 return 不同的事情,但是这个错误让我很困惑,我不知道如何 google 它。

我的想法是,我有一个“2dvector”class,我想 return 将点积转换为单个值而不是向量形式。 例子: float dproduct = vec_a * vec_b;

我已经成功地将“*”重载为我的 class 的点积。虽然我对如何取两个 class 感到困惑,但将点积作为单个值,并将其 return 转换为不同的类型。

我目前的想法是:

const float operator= (vec2& right);

const float vec2::operator= (vec2& right){
return (right.x + right.y);
}

由于右侧应该正确评估,因为 vec_a * vec_b 将 return 得到 "vec_c" 结果。

对于 vec_a * vec_b 部分,您需要一个 operator*() 来计算两个 vec2 对象和 return 一个新的 vec2 的乘积,例如:

vec2 operator* (const vec2 &left, const vec2 &right)
{
    vec2 tmp;
    // fill with the product of left and right...
    return tmp;
}

对于float dproduct = ...部分,需要转换运算符将单个vec2转换为数字:

class vec2
{
public:
    operator float () const;
};

vec2::operator float () const
{
    return (this.x + this.y);
}

哇,这个声明:

float dproduct = vec_a * vec_b;

相当于这一系列的调用:

float dproduct = ::operator*(vec_a, vec_b).operator float();