c++ - 将多个运算符与运算符重载一起使用会产生奇怪的错误

标签 c++ c++11 operator-overloading

我有一个名为 FloatTensor 的类。我在其中为 + 和 * 重载了运算符。这是代码。


class FloatTensor {
    public:
    float val; // value of tensor 
    float grad; // value of grad
    Operation *frontOp =NULL, *backOp =NULL;
    FloatTensor* two;
    FloatTensor() {
        // default
    }

    FloatTensor(float val) {
        this->val = val;
    }

    FloatTensor(float val, Operation* op) {
        this->val = val;
        this->backOp = op;
    }

    void backward(float grad) {
        this->grad = grad;
        if(this->backOp != NULL) {
            this->backOp->backward(grad);
        }
    }
    FloatTensor exp() {
        this->frontOp = new ExponentOperation(this);
        return this->frontOp->compute();
    }

    FloatTensor operator * (FloatTensor &two) { 

        this->frontOp = new MultiplyOperation(this, &two);
        return this->frontOp->compute();
    }

    FloatTensor operator + (FloatTensor &two) { 
        this->frontOp = new AddOperation(this, &two);
        return this->frontOp->compute();
    }

    FloatTensor operator / (FloatTensor &two) { 

        this->frontOp = new DivideOperation(this, &two);
        return this->frontOp->compute();
    }

};

在我的主函数中,当我尝试简单重载时,一切正常

int main() {

    // X 
    FloatTensor x1(200); // heap declaration
    FloatTensor x2(300);

    // Weights
    FloatTensor w1(222);
    FloatTensor w2(907);

    FloatTensor temp = (x1*w1);

}

然而,当我尝试用更多像这样的运算符重载这个公式时

int main() {

    // X 
    FloatTensor x1(200); // heap declaration
    FloatTensor x2(300);

    // Weights
    FloatTensor w1(222);
    FloatTensor w2(907);

    FloatTensor temp = (x1*w1) + (x2*w2);

}

我收到这个错误:

no operator "+" matches these operands -- operand types are: FloatTensor + FloatTensor

如果有人能解释为什么会这样,我将不胜感激。我观察到这有效:

x1*w1*x2*x1;
x1*w1 + x2;

但是 x1*w1 + x2*w2 没有。

很奇怪..

最佳答案

您的运算符接受一个非const 左值引用作为参数。临时对象不绑定(bind)到非 const 左值引用。要接受临时对象,请使用:

FloatTensor operator + (const FloatTensor &two)

关于c++ - 将多个运算符与运算符重载一起使用会产生奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54670894/

相关文章:

c++ - 乘法运算符正在改变原始值

c++ - 在 namespace 内的 lambda 中使用时找不到运算符重载

c++ - MFC。在 RichEditCtrl 中快速高亮所有匹配项

c++ - 未显示 libstdc++-v3 中的 GCC 源代码修改

c++ - 从 C++ 客户端通过 TCP 将数据发送到 JSON 服务器

c++ - 如何将3D尺寸不固定的3D数组展平为1D数组?

c++ - 为什么编译器无法在我的代码中推断出模板参数?

c++ - 我如何估计 std::map 的内存使用情况?

c++11 - C++ 迭代器不匹配错误

Python:rtruediv 没有像我预期的那样工作