CPP:重载的嵌套运算符无法正常工作

pro*_*bie 0 c++ operator-overloading

我重写了添加操作,这样我就可以添加我的struct Vec3的两个向量

// addition
Vec3 operator+(Vec3<T> &other) {
    return Vec3(this->x + other.x, this->y + other.y, this->z + other.z);
}
// product with one scalar
Vec3 operator*(float scalar) {
    return Vec3(this->x * scalar, this->y * scalar, this->z * scalar);
}
Run Code Online (Sandbox Code Playgroud)

Vec3只有T型的三个属性.

使用它时T是浮点数,我执行此代码:

vec temp = vecOne * skalarOne + vecTwo * scalarTwo;
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

二元运算符'+'不能应用于'pray :: Vec3'和'pray :: Vec3'类型的表达式

如果首先计算乘法并将结果保存在向量中然后执行向量加法,则不会出现此错误.

有人有什么想法?谢谢!

Bat*_*eba 5

您需要将功能签名更改为

Vec3 operator+(const Vec3<T> &other) const

&c.,否则匿名临时无法绑定到它.