【问题标题】:CPP: Overloaded nested operator not workingCPP:重载的嵌套运算符不起作用
【发布时间】:2016-12-07 13:42:16
【问题描述】:

我重写了加法操作,这样我就可以添加我的 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);
}

Vec3 只有 T 型的三个属性。

当使用它时,T 是一个浮点数,我执行这段代码:

vec temp = vecOne * skalarOne + vecTwo * scalarTwo;

我得到这个错误:

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

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

有人知道吗?谢谢!

【问题讨论】:

  • Vec3& 运算符+(..), Vec3& 运算符*(...)。应该有对 Vec3 的引用。

标签: c++ operator-overloading


【解决方案1】:

您需要将函数签名更改为

Vec3 operator+(const Vec3&lt;T&gt; &amp;other) const

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

【讨论】:

    【解决方案2】:

    您应该像这样返回对 vec3 的引用:

    // addition
    Vec3 operator+(const Vec3& other) {
        return { x + other.x, y + other.y, z + other.z };
    }
    // product with one scalar
    Vec3 operator*(float scalar) {
        return { x * scalar, y * scalar, z * scalar };
    }
    

    编辑:这是我完整的可运行解决方案,如果上面的修复对你不起作用。

    template <typename T>
    class Vec3 {
    public:
        Vec3(T x, T y, T z) : x(x), y(y), z(z) {}
        T x;
        T y;
        T z;
    
        // addition
        Vec3 operator+(const Vec3<T>& other) {
            return { x + other.x, y + other.y, z + other.z };
        }
        // product with one scalar
        Vec3 operator*(float scalar) {
            return { x * scalar, y * scalar, z * scalar };
        }
    };
    
    int main() {
        Vec3<float> a(2, 2, 2);
        Vec3<float> b(1, 2, 3);
        float num = 3;
        Vec3<float> c = a + b;
        Vec3<float> d = a * num;
        Vec3<float> e = a * num + b * num;
    }
    

    【讨论】:

    • 吊着?你这是什么意思?
    • 是的,我现在已经更正了。当前的解决方案现在有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多